我有包含尾随时间戳的字符串值。我想我可以使用 strptimewith一个正则表达式模式来提取这些。
Like:
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'))
Gives:
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'
只是想知道:这是否可能 - 将正则表达式模式放入该格式字符串中?如果没有,那么让我到达那里的直接规范方法是什么?
不,不能,仅支持固定文本(即文字)和日期时间组件。
只需先提取日期时间部分;你可以使用正则表达式那个任务当然。并不是说需要那个在你的例子中,因为日期时间部分是末尾的固定宽度文本块:
datetime.strptime(input_with_ts[-13:], '%Y%m%d_%H%M')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)