How to print the date and time according to the user's time zone setting

I use GAE ndb for data storage and have a date property defined as

 class GuestMessage(ndb.Model): date = ndb.DateTimeProperty(auto_now_add=True) 

So now I can easily print it using e.date.strftime('%Y-%m-%d %H:%M:%S') and get 2013-06-03 05:46:50

But how can I print it as 2013-06-03 05:46:50 +0000 or 2013-06-03 13:46:50 +0800 according to the user's time zone setting?

+4
source share
1 answer

The datetime object does not have a tzinfo object. So please try this

 import pytz from pytz import timezone query = GuestMessage.all().get() current = query.date user_tz = timezone('Asia/Singapore') current = current.replace(tzinfo=pytz.utc).astimezone(user_tz) self.response.write(current.strftime('%Y-%m-%d %H:%M:%S %z')) # 2013-05-22 19:54:14 +0800 self.response.write(current.strftime('%Y-%m-%d %H:%M:%S %Z')) # 2013-05-22 19:54:14 SGT 

To find the time zone from the request header:

 county_code = self.request.headers['X-Appengine-Country'] # Return County code like SG, IN etc. tz = pytz.country_timezones(county_code) 

If you get ImportError: No module named pytz , download the source here: pypi.python.org/pypi/gaepytz . Then move pytz dir to the root of your application engine project.

+4
source

Source: https://habr.com/ru/post/1484130/


All Articles