我可以帮您翻译成中文:我可以在datetime.strptime格式中使用正则表达式吗?

6

我有一些包含时间戳的字符串值。我认为我可以使用带有正则表达式模式的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'))

提供:

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'

我想知道是否可以将正则表达式模式放入该格式字符串中?如果不行,那么有什么直接的标准方法可以实现这一点吗?

1个回答

12

不可以,仅支持固定文本(字面量)和日期时间组件。

首先提取日期时间部分;当然,您可以使用正则表达式来完成这个任务。在您的示例中并不需要这样做,因为日期时间部分是文本末尾的固定宽度文本块。

datetime.strptime(input_with_ts[-13:], '%Y%m%d_%H%M')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接