Python datetime.strptime - ValueError:时间数据与格式不匹配

时间:2018-01-01 20:22:27

标签: python datetime

我是Python新手。我尝试编写将从文件中读取的程序并将其写入数据库。我的部分代码是:

a = ("X" + a).trim().substring(1);

当我运行脚本时出现此错误:

import datetime

format = '[%d/%b/%Y:%I:%M:%S '
mytime = '[29/Oct/2017:13:11:38 '
now = datetime.datetime.strptime(mytime, format)

我不明白这个错误。它符合格式。没有额外的空间或类似的东西。我使用这两行代码

 now = datetime.datetime.strptime(mytime, format)
  File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
    (data_string, format))
ValueError: time data '[29/Oct/2017:13:11:38 ' does not match format '[%d/%b/%Y:%I:%M:%S '

在另一个程序中,它工作正常。哪里有问题?

1 个答案:

答案 0 :(得分:3)

查看the docs%I匹配AM / PM格式的小时数,表示有效值范围为01到12.您有13(下午1点)

我猜您需要使用%H

import datetime

mytime = '[29/Oct/2017:13:11:38 '
fmt = '[%d/%b/%Y:%H:%M:%S '
now = datetime.datetime.strptime(mytime, fmt)
print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S'))

打印:

now: 2017-10-29 13:11:38

检查一下:

fmt = '[%d/%b/%Y:%I:%M:%S '

for test in range(1, 24):
    mytime = '[29/Oct/2017:%02d:11:38 ' % test
    now = datetime.datetime.strptime(mytime, fmt)
    print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S'))

工作“正常”(我引用,因为12被假定为午夜),直到test点击13

now: 2017-10-29 01:11:38
now: 2017-10-29 02:11:38
now: 2017-10-29 03:11:38
now: 2017-10-29 04:11:38
now: 2017-10-29 05:11:38
now: 2017-10-29 06:11:38
now: 2017-10-29 07:11:38
now: 2017-10-29 08:11:38
now: 2017-10-29 09:11:38
now: 2017-10-29 10:11:38
now: 2017-10-29 11:11:38
now: 2017-10-29 00:11:38
Traceback (most recent call last):
  File "./stack_096.py", line 12, in <module>
    now = datetime.datetime.strptime(mytime, fmt)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '[29/Oct/2017:13:11:38 ' does not match format '[%d/%b/%Y:%I:%M:%S '