Getting current time with timezone in python?

2019-06-28 06:01发布

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

3条回答
一夜七次
2楼-- · 2019-06-28 06:25

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?

查看更多
戒情不戒烟
3楼-- · 2019-06-28 06:30

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 )

查看更多
三岁会撩人
4楼-- · 2019-06-28 06:32

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
查看更多
登录 后发表回答