Python - strptime ValueError:时间数据与格式'%Y /%m /%d'不匹配

时间:2013-09-09 21:54:26

标签: python datetime strptime

我相信我错过了一些微不足道的东西。在阅读了有关strptime ValueError的所有问题后,我觉得格式似乎正确,以下是我得到的以下错误

Traceback (most recent call last):
  File "loadScrip.py", line 18, in <module>
    nextDate = datetime.datetime.strptime(date, "%Y/%m/%d")
  File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'

我在Linux x86_64下使用Python 2.6.6。任何帮助都感激不尽。

2 个答案:

答案 0 :(得分:8)

您的错误表示您的数据中包含字母l(小写L),而不是年份中的数字1

ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'

这不是符合所请求格式的有效日期;用l替换1,输入日期就可以了:

>>> import datetime
>>> datetime.datetime.strptime('20l2/08/25', "%Y/%m/%d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
>>> datetime.datetime.strptime('2012/08/25', "%Y/%m/%d")
datetime.datetime(2012, 8, 25, 0, 0)

修改您的输入,格式正确。

答案 1 :(得分:-1)

Here's how to do it with the string variable: >>> start_day = 2015188 >>> print start_day 2015188 >>> print conv time.struct_time(tm_year=2015, tm_mon=7, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=188, tm_isdst=-1) >>> conv = time.strptime( str(start_day), "%Y%j" ) >>> print conv time.struct_time(tm_year=2015, tm_mon=7, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=188, tm_isdst=-1) For whatever reason, you have to put the string variable inside the str() thing and all the examples I have found online only show the date in quotes.