将UTC datetime转换为用户的本地日期和时间 [英] Converting UTC datetime to user's local date and time

查看:156
本文介绍了将UTC datetime转换为用户的本地日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django和Google App Engine上使用python。我也在我的一个模型中使用DateTimeProperty。偶尔我想向用户显示日期和时间。

I'm using python on Django and Google App Engine. I'm also using the DateTimeProperty in one of my models. Occasionally I would like to display that date and time to the user.

最好将存储在DateTimeProperty中的datetime转换为用户的日期时间?

What is the best to convert the datetime stored in DateTimeProperty into the user's datetime?

还是更精确解决问题的方法:获取客户端时区并将python datetime对象转换为本地时间的最佳方式是什么?

Or a more precise way of framing the question: What is the best way to get a client's timezone and convert a python datetime object into their own local time?

推荐答案

这是一个比GAE更好的Python问题,除非GAE有一些基础设施来促进这个(我做了一个快速扫描,但没有找到任何参考)。

This is more a Python question, than a GAE one, unless GAE has some infrastructure to facilitate this (I've made a quick scan but haven't found any reference).

基本上,您希望以UTC时区(例如使用datetime.datetime.utcnow)和用户时区存储日期/时间,您可以尝试从用户IP中提取(使用GeoDjango,如果在GAE上可用,或pygeoip;您需要一些地理位置数据块,如: http://www.maxmind.com/app/geolitecity),或明确询问用户 - 这具有可以要求描述性时区n的优点嗯,像欧洲/华沙。如果你要求UTC + 2,那么你会丢失任何DST转移的指示。

Basically, you want to store date/times in UTC timezone (e.g. use datetime.datetime.utcnow) along with user timezones, which you can either try to extract from user IPs (using GeoDjango, if avaiable on GAE, or pygeoip; you need some geolocation db like: http://www.maxmind.com/app/geolitecity), or to explicitly ask users about it - which has the advantage that you can ask for a descriptive timezone name, like "Europe/Warsaw". If you ask for just UTC+2, then you loose any indication of DST shifts.

然后,你可以从utc转换到所需的时区。 pytz

Then, you can shift from utc to the desired timezone using e.g. pytz:

import pytz
local_tz = pytz.timezone(timezone_name)
return timestamp_utc.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None)

- 其中 timestamp_utc 是要转换的utc datetime,而timezone_name是所提到的欧洲/华沙。

-- where timestamp_utc is utc datetime that you want to convert, and timezone_name is the mentioned "Europe/Warsaw".

(请注意,我不知道这些作品在GAE中哪一个,但至少你会知道要查找的内容)

(Note that I don't know which of these works in GAE, but at least you will know what to look for)

这篇关于将UTC datetime转换为用户的本地日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆