我有包含尾随时间戳的字符串值.我以为我可以使用strptime 和正则表达式来提取那些.
喜欢:
from __future__ import print_function
from datetime import datetime
# this here works
input_with_ts = "20170410_1133"
print(datetime.strptime(input_with_ts, '%Y%m%d_%H%M'))
# but this is how things really look like
input_with_ts = "foo_bar_D31_848_20170410_1133"
print(datetime.strptime(input_with_ts, 'foo_bar_.*_.*_%Y%m%d_%H%M'))
Run Code Online (Sandbox Code Playgroud)
得到:
2017-04-10 11:33:00
Traceback (most recent call last):
File "test.py", line 9, in <module>
print(datetime.strptime(input_with_ts, 'foo_bar_.*_.*_%Y%m%d_%H%M'))
File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data 'foo_bar_D31_848_20170410_1133' does not match format 'foo_bar_.*_.*_%Y%m%d_%H%M'
Run Code Online (Sandbox Code Playgroud)
简单地想知道:甚至可能 - 将正则表达式模式放入该格式字符串中?如果没有,那么让我在那里的直接规范方法是什么?
不,你不能,只支持固定文本(如此文字)和日期时间组件.
只需先提取日期时间部分; 当然,你可以使用正则表达式执行该任务.并非您的示例中需要这样,因为日期时间部分是最后一个固定宽度的文本块:
datetime.strptime(input_with_ts[-13:], '%Y%m%d_%H%M')
Run Code Online (Sandbox Code Playgroud)