Python:在字符串中匹配自定义日期格式

shi*_*shu 2 python datetime date

我有一个像这样的字符串:

>>> string = "bla_bla-whatever_2018.02.09_11.34.09_more_bla-123"
Run Code Online (Sandbox Code Playgroud)

我需要从中提取日期2018.02.09_11.34.09.它将始终采用这种格式.

所以我尝试过:

>>> match = re.search(r'\d{4}\.\d{2}\.\d{2}_\d{2}\.\d{2}\.\d{2}', string)
Run Code Online (Sandbox Code Playgroud)

它正确地从该字符串中提取出日期:

>>> match.group()
'2018.02.09_11.34.09'
Run Code Online (Sandbox Code Playgroud)

但是当我尝试从这个字符串创建一个datetime对象时,它不起作用:

>>> datetime.datetime.strptime(match.group(), '%Y.%m.%d_%H.%I.%S')
ValueError: time data '2018.02.09_11.34.09' does not match format '%Y.%m.%d_%H.%I.%S'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

hee*_*ayl 6

你需要%I%M几分钟替换格式说明符:

%Y.%m.%d_%H.%M.%S
Run Code Online (Sandbox Code Playgroud)

%I表示12小时格式的小时,因此从(0)1..12开始,而根据您的示例,您有34作为值,大概是以分钟(%M)为单位.