向naive datetime添加时区偏移量(ISO 8601格式)



我需要将一系列朴素日期时间转换为其本地时区。本地tz单独存储为ISO8601格式(例如:'-0800' (PST).

我已经尝试用一个新的日期时间替换,添加偏移量:

>>>utc_time 
datetime.datetime(2014, 1, 24, 0, 32, 30, 998654)
>>>tz_offset
u'-0800'
>>>local_time = utc_time.replace(tzinfo=tz_offset)
*** TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'unicode'

并尝试使用pytz来本地化(),这需要先调用timezone():

>>>timezone(tz_offset)
*** UnknownTimeZoneError: '-0800'

*doc用于此步骤:http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

有什么建议让这些补偿工作吗?

同一时区在不同日期可能有不同的utc偏移量。使用时区名称代替字符串utc偏移量:

import datetime
import pytz # $ pip install pytz
utc_time = datetime.datetime(2014, 1, 24, 0, 32, 30, 998654)
utc_dt = utc_time.replace(tzinfo=pytz.utc) # make it timezone aware
pc_dt = utc_dt.astimezone(pytz.timezone('America/Los_Angeles')) # convert to PST
print(pc_dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
# -> 2014-01-23 16:32:30.998654 PST-0800

正如错误消息所说,您需要tzinfo子类(即tzinfo对象),pytz.timezone从时区字符串返回,但它不理解您提供的偏移量格式。

另一个与你的问题相关的线程,它链接到这个谷歌应用程序引擎应用程序,它也提供了一些源代码。如果你愿意,这里有一个简单的例子。

class NaiveTZInfo(datetime.tzinfo):
    def __init__(self, hours):
        self.hours = hours
    def utcoffset(self, dt):
        return datetime.timedelta(hours=self.hours)
    def dst(self, dt):
        return datetime.timedelta(0)
    def tzname(self, dt):
        return '+%02d' % self.hours

要处理偏移量格式,必须为所提供的格式编写自己的解析逻辑。

>>> t = NaiveTZInfo(-5)
>>> u = datetime.datetime(2014, 1, 24, 0, 32, 30, 998654)
>>> v = u.replace(tzinfo=t)
>>> str(v)
'2014-01-24 00:32:30.998654-05:00'

最新更新