In Google App Engine, I used nowTime = datetime.datetime.now()
to get the system time. However, I found it is different from the computer system time. For example, nowTime
is 2012-12-20 14:44:30.910192
, but my computer system time is 2012-12-20 22:44
. There is an eight-hour difference. Is it because of the time zone? Where does Google App Engine SDK get time from? Thanks.
Asked
Active
Viewed 967 times
2

RocketDonkey
- 36,383
- 7
- 80
- 84

Randy Tang
- 4,283
- 12
- 54
- 112
-
Remember that your users may be in totally different time zones. – Andrei Volgin Dec 20 '12 at 23:54
1 Answers
5
See http://timezones.appspot.com/ - GAE time zones will always be in UTC
, which is why you are seeing the 8-hour difference. Per the site:
The runtime's TZ environment variable is set to UTC, and can't be changed. Timestamps returned by e.g. time.time() and datetime.datetime.now() will always be in UTC. Similarly, datetime properties in the datastore will always be stored and returned as UTC.
You can change the time zone of a datetime in memory with the astimezone() method. If datetime's tzinfo member isn't set, you'll first need to set it to a UTC tzinfo with the replace() method.
You can also see it documented here, with an example of how to do special handling.

RocketDonkey
- 36,383
- 7
- 80
- 84
-
No wonder! Thanks. BTW, how do I change the time into UTC? I need to measure time length by: datetime.datetime.now() - datetime.datetime(2012, 1, 1, 0, 0, 0) – Randy Tang Dec 20 '12 at 15:17
-
1@Yuan-LiangTang Ha, time stuff still baffles me, regardless of how much time I spend reading about it :) One thing you can try is taking the current time (`t = time.time()`), converting it into UTC by doing `utc = time.gmtime(t)`, feeding it into `mktime` to get seconds since the epoch (`time.mktime(utc)`) and then feeding that into `datetime.datetime.fromtimestamp` to get a `datetime` object. See http://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object for a better overview, and good luck with everything! – RocketDonkey Dec 20 '12 at 15:42
-
@Greg Ha, yeah, if he doesn't need the microseconds (which I'm assuming he doesn't), that is a much better way to go (assuming shorter, easier to digest and faster to implement is better, of course :) ). – RocketDonkey Dec 20 '12 at 19:12