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

我有以下代码(基于 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"

以上打印:

$python parse_log.py
did NOT match date format

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

$date  '+%b %d,%Y %-I'
Apr 14,2016 1

我错过了什么?

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

try:
    datetime.datetime.strptime("Apr 14,2016 ",%Y ')
    print "matched date format"
except ValueError:
    print "did NOT match date format"

输出

$python parse_log.py
matched date format

我在python 2.6.6上.

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

datetime.datetime.strptime("Apr 14,2016 9:59:54",%Y %-I:%M:%s')

解决方法

你需要删除 – 为 strptime

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

In [17]: print  datetime.datetime.strptime("Apr 14,%Y %I:%M:%s')
2016-04-14 09:59:54

-I仅用于strftime

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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...