如何将包含 BST(英国夏令时)的时间戳字符串解析为时区感知日期时间戳?
How do I parse timestamp strings which contain BST (British Summer Time) into a timezone aware datetime timestamp?
我有格式为“25-Oct-20 1:00:00 AM GMT”和“25-Oct-20 12:00:00 AM BST”的时间戳,我希望将它们解析为时区感知约会时间。我试过使用 strptime 格式 "%d-%b-%y %I:%M:%S %p %Z"
但是 datetime.strptime 的 %Z 参数无法将 BST 识别为有效输入,我无法找出处理夏令时解析的“正确”方法。
如果您查看来自 dateutil
的错误,它表示如下内容:
UnknownTimezoneWarning: tzname BST identified but not understood.
Pass `tzinfos` argument in order to correctly return a timezone-aware
datetime. In a future version, this will raise an exception.
换句话说,您可以传入将时区别名(如“BST”)映射到适当时区信息的字典。可能是这样的:
>>> import dateutil.parser
>>> import dateutil.tz
>>> BST = dateutil.tz.gettz('Europe/London')
>>> dateutil.parser.parse('25-Oct-20 12:00:00 AM BST', tzinfos={'BST': BST})
datetime.datetime(2020, 10, 25, 0, 0, tzinfo=tzfile('/usr/share/zoneinfo/Europe/London'))
我有格式为“25-Oct-20 1:00:00 AM GMT”和“25-Oct-20 12:00:00 AM BST”的时间戳,我希望将它们解析为时区感知约会时间。我试过使用 strptime 格式 "%d-%b-%y %I:%M:%S %p %Z"
但是 datetime.strptime 的 %Z 参数无法将 BST 识别为有效输入,我无法找出处理夏令时解析的“正确”方法。
如果您查看来自 dateutil
的错误,它表示如下内容:
UnknownTimezoneWarning: tzname BST identified but not understood.
Pass `tzinfos` argument in order to correctly return a timezone-aware
datetime. In a future version, this will raise an exception.
换句话说,您可以传入将时区别名(如“BST”)映射到适当时区信息的字典。可能是这样的:
>>> import dateutil.parser
>>> import dateutil.tz
>>> BST = dateutil.tz.gettz('Europe/London')
>>> dateutil.parser.parse('25-Oct-20 12:00:00 AM BST', tzinfos={'BST': BST})
datetime.datetime(2020, 10, 25, 0, 0, tzinfo=tzfile('/usr/share/zoneinfo/Europe/London'))