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

该博客讨论了在Python中使用`datetime.strptime()`函数解析包含时间区信息的日期时间字符串时遇到的问题。错误源于 `%m` 指令不匹配月份的缩写。解决方案包括使用 `%b` 或 `%B` 代替 `%m` 来处理月份名称,并在必要时剥离时区信息。还提到了使用`dateutil.parser`模块作为替代解析方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 '

Whats wrong with this?

解决方案

%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.

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

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).

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)

but

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

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)

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值