将时区偏移量(ISO 8601格式)添加到NaiveDateTim

2024-04-28 22:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把一系列天真的日期时间转换成它们的本地tz。本地tz以ISO8601格式单独存储(例如PST的“-0800”)。在

我尝试用新的日期时间替换日期时间,并添加偏移量:

>>>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进行localize(),这需要先调用timezone():

^{pr2}$

*此步骤的文档:http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

有什么建议可以让这些补偿发挥作用?在

*类似的问题here但我认为使用了不同的格式。在


Tags: datetimetimelocal格式时间replacetzoffset
2条回答

如错误消息所述,您需要一个tzinfo子类(即tzinfo object),该子类pytz.timezone从时区字符串返回,但它不理解您提供的偏移格式。在

Another relevant thread to your problem,它链接到这个google app engine application,它还提供一些源代码。如果你愿意的话,这里有一个简单明了的例子。在

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

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

^{pr2}$

同一时区在不同日期可能有不同的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

相关问题 更多 >