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

标签 python string datetime date-parsing

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/

相关文章:

python - 如果它存在于上一组中,则删除行

字符串指针与数组

c# - 调用System.DateTime.Now的速度

c# - 字符串未被识别为 DateTime.ParseExact 的有效日期时间异常

c++ - 为什么这个 time_zone_ptr 示例不包含内存泄漏?

python - 处理字典两点之间的距离

python - 使用 Jinja 过滤器创建内容片段

python 2.7 : Themed "common dialog" tkinter interfaces via Ttk?

java - 如何在字符串中查找第 n 个出现的字符?

c - 释放 malloc 不会删除 char 数据