gpt4 book ai didi

python时间字符串与格式不匹配

转载 作者:行者123 更新时间:2023-11-28 21:54:45 25 4
gpt4 key购买 nike

def deadlines(t):
'''shows pretty time to deadlines'''
fmt = '%a %d %m %Y %I:%M %p %Z'

dt = datetime.strptime( t , fmt )

print 'dt ', repr(dt)


first = 'Sun 11 May 2014 05:00 PM PDT'
deadlines(first)

ValueError: time data 'Sun 11 May 2014 02:00 PM PDT' does not match format ' %a %d %m %Y %I:%M %p %Z '

这有什么问题吗?

最佳答案

%m 匹配以两位小数表示的月份(在 [01, 12] 中)。使用 %b 作为缩写月份名称,或使用 %B 作为完整月份名称:

fmt = '%a %d %b %Y %I:%M %p %Z'

可以找到显示日期格式指令及其含义的表格 here .


如果您在使用 %Z 解析 PDT 时遇到问题:

根据 time.strptime docs :

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

因此,如果在没有 PDT 的情况下解析日期字符串有效:

In [73]: datetime.strptime('Sun 11 May 2014 05:00 PM', '%a %d %b %Y %I:%M %p')
Out[73]: datetime.datetime(2014, 5, 11, 17, 0)

但是

datetime.strptime('Sun 11 May 2014 05:00 PM PDT', '%a %d %b %Y %I:%M %p %Z')

引发 ValueError,然后您可能需要去掉时区名称(它们是 in general, ambiguous anyway):

In [10]: datestring = 'Sun 11 May 2014 05:00 PM PDT'

In [11]: datestring, _ = datestring.rsplit(' ', 1)

In [12]: datestring
Out[12]: 'Sun 11 May 2014 05:00 PM'

In [13]: datetime.strptime(datestring, '%a %d %b %Y %I:%M %p')
Out[13]: datetime.datetime(2014, 5, 11, 17, 0)

或使用 dateutil :

In [1]: import dateutil.parser as parser

In [2]: parser.parse('Sun 11 May 2014 05:00 PM PDT')
Out[2]: datetime.datetime(2014, 5, 11, 17, 0)

关于python时间字符串与格式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com