Converting UTC datetime to user's local date a

2020-06-04 09:04发布

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.

What is the best to convert the datetime stored in DateTimeProperty into the user's 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?

3条回答
我命由我不由天
2楼-- · 2020-06-04 09:13

So I did a bit more research into this. To correctly do timezones, you have to follow something like what Tomasz described in his answer. However, if you're willing to tolerate a bit of kludge, you can get 90% of the way there with much less effort.

When the user logs in or does any action on your site, you can use javascript to get their current timezone offset and then send it in your next request:

var offset = (new Date()).getTimezoneOffset()
$.post("post.html", "offset="offset.toString(), ... );

Of course this assumes that the user has correctly set their current timezone. This is discussed on a number of other websites:

查看更多
我命由我不由天
3楼-- · 2020-06-04 09:26

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).

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.

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)

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

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

查看更多
神经病院院长
4楼-- · 2020-06-04 09:33

Best and easy way for converting Google App Engine datetime in templates:

http://code.google.com/p/dateconv4gae/

查看更多
登录 后发表回答