即使bash识别它,日期时间模式在python中也不匹配

Lid*_*dia 4 python datetime

我有以下代码(基于http://strftime.org/):

try:
    datetime.datetime.strptime("Apr 14, 2016 9", '%b %d, %Y %-I')
    print "matched date format"
except ValueError:
    print "did NOT match date format"
Run Code Online (Sandbox Code Playgroud)

以上打印:

$ python parse_log.py
did NOT match date format
Run Code Online (Sandbox Code Playgroud)

但是bash会识别这种日期格式:

$ date  '+%b %d, %Y %-I'
Apr 14, 2016 1
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

似乎%-I是问题,因为Python匹配没有%-I部分的日期:

try:
    datetime.datetime.strptime("Apr 14, 2016 ", '%b %d, %Y ')
    print "matched date format"
except ValueError:
    print "did NOT match date format"
Run Code Online (Sandbox Code Playgroud)

输出:

$ python parse_log.py
matched date format
Run Code Online (Sandbox Code Playgroud)

我在python 2.6.6上.

我需要匹配的实际模式使用12小时时钟,并且是:

datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %-I:%M:%S')
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 5

你需要删除-for strptime:

 '%b %d, %Y %I:%M:%S'

In [17]: print  datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %I:%M:%S')
2016-04-14 09:59:54
Run Code Online (Sandbox Code Playgroud)

-I只用于的strftime:

In [15]: print datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %I:%M:%S').strftime('%b %d, %Y %-I:%M:%S')
Apr 14, 2016 9:59:54
Run Code Online (Sandbox Code Playgroud)