Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use regexes within datetime.strptime formats?

I have string values that contain a trailing time stamp. I thought I could use strptime with a regex pattern to extract those.

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'

Simply wondering: is that even possible - putting a regex pattern into that format string? If not, what is the straight canonical way to get me there?

like image 469
GhostCat Avatar asked Dec 23 '22 19:12

GhostCat


1 Answers

No, you can't, only fixed text (so literals) and date-time components are supported.

Just extract the datetime portion first; you can use a regex for that task of course. Not that that is needed in your example, because the datetime portion is a fixed-width chunk of text at the end:

datetime.strptime(input_with_ts[-13:], '%Y%m%d_%H%M')
like image 146
Martijn Pieters Avatar answered Jan 11 '23 00:01

Martijn Pieters