我有以下代码(基于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)
你需要删除-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)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |