问题描述
我的时间戳格式为格林威治标准时间25年10月20日1:00:00".和"BST 25-Oct-20 12:00:00 AM"我希望将它们解析为可识别时区的日期时间.我尝试使用strptime格式%d-%b-%y%I:%M:%S%p%Z"
I have timestamps of the format "25-Oct-20 1:00:00 AM GMT" and "25-Oct-20 12:00:00 AM BST" and I wish to parse them into a timezone aware datetime. I have tried using the strptime format "%d-%b-%y %I:%M:%S %p %Z"
然而,datetime.strptime的%Z参数不能将BST识别为有效输入,因此我无法弄清正确"的BST.解析夏令时的方法.
However the %Z argument of datetime.strptime does not recognize BST as a valid input, and I can not figure out the "correct" way to handle parsing daylight savings times.
推荐答案
如果您查看 dateutil
中的错误,则会显示类似以下内容:
If you look at the error from dateutil
, it says something like:
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")映射到适当的时区信息的字典.也许像这样:
In other words, you can pass in a dictionary that maps timezone aliases (like "BST") to appropriate timezone information. Maybe something like:
>>> 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'))
这篇关于如何将包含BST(英国夏令时)的时间戳字符串解析为可识别时区的datetime时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!