问题
I'm using Google App Engine with python. And I can't install third party library.
I though this should work, but it actually runs without error but it returns current time timezone is not applied.
What did I do wrong?
from datetime import tzinfo, timedelta, datetime
class Seoul_tzinfo(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=9)
def dst(self, dt):
return timedelta(0)
greeting.date = datetime.now( Seoul_tzinfo() )
回答1:
Are you talking about when the entity is fetched from the database? If so, appengine stores all dt properties in UTC; when you put(), it simply discards the tz info. The wisest thing would be to convert your dt to UTC (using astimezone()), and convert back when you fetch it from the datastore.
(See http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#DateTimeProperty )
回答2:
You need to implement a tzinfo class with ALL the proper methods to do what you want to do.
The documentation says that tzinfo is an abstract class that if to be used with datetime objects needs to be made a concrete class with proper methods.
Specifically take a look at this from the documentation:
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
回答3:
I'm running python 2.6.5 and your code seems to work fine. I tweaked it to output my local time and your time adjusted one;
$ python test.py
Local: 2011-03-03 08:53:43.514784
Adj: 2011-03-03 22:53:43.514784+09:00
Are you sure it's not something having to do with your greeting class?
来源:https://stackoverflow.com/questions/5180889/getting-current-time-with-timezone-in-python