python时间字符串与格式不匹配 [英] python time string does not match format

查看:288
本文介绍了python时间字符串与格式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:时间数据'Sun 2014年5月11日02:00 PM PDT'与格式'%a%d%m%Y%I:%M%p%Z'

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 用作完整的月份名称:

%m matches months represent as a two-digit decimal (in [01, 12]). Use %b for abbreviated month names, or %B for full month names instead:

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

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

A table showing the date format directives and their meanings can be found here.

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

If you're having trouble parsing PDT using %Z:

每个 time.strptime文档


对%Z指令的支持基于
tzname中包含的值以及daylight是否为true。因此,它是特定于
的平台,除了可以识别始终为
的UTC和GMT(并被视为非夏时制时区)。

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的情况下分析日期字符串的工作原理:

So, if parsing the date string without PDT works:

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,那么您可能需要去除时区名称(它们是总的来说,还是模棱两可的):

raises a ValueError, then you may need strip off the timezone name (they are, 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时间字符串与格式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆