簡體   English   中英

將時區偏移量(ISO 8601格式)添加到原始日期時間

[英]Add time zone offset (in ISO 8601 format) to naive datetime

我需要將一系列幼稚的日期時間轉換為其本地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():

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

*此步驟的文檔: 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從時區字符串返回,但是它不理解您提供的偏移格式。

與您的問題相關的另一個主題 ,該主題鏈接到此Google App Engine應用程序 ,該應用程序還提供一些源代碼。 如果您願意,這是一個快速而幼稚的示例。

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM