我正在尝试将日期字符串转换为日期格式
>>> str = "04-18-2002 03:50PM"
>>> time.strptime(str, '%m-%d-%Y %H:%M%p')
time.struct_time(tm_year=2002, tm_mon=4, tm_mday=18, tm_hour=3, tm_min=50, tm_sec=0, tm_wday=3, tm_yday=108, tm_isdst=-1)
然而,当年份是两位数时,它会中断
>>> str = "04-18-02 03:50PM"
>>> time.strptime(str, '%m-%d-%Y %H:%M%p')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '04-18-02 03:50' does not match format '%m-%d-%Y %H:%M'
有什么想法吗??
最佳答案
格式字符串中的
%Y
表示四位数年份,参见 documentation .对于两位数的年份,请改用 %y
。要支持这两种格式,请首先尝试:
其中一种格式,捕获ValueError
并尝试另一种格式。
关于当年份是两位数时,python从字符串中断转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988905/