2

I have a string like this:

>>> string = "bla_bla-whatever_2018.02.09_11.34.09_more_bla-123"

I need to extract the date 2018.02.09_11.34.09 from it. It will always be in this format.

So I tried:

>>> match = re.search(r'\d{4}\.\d{2}\.\d{2}_\d{2}\.\d{2}\.\d{2}', string)

It correctly extracts out the date from that string:

>>> match.group()
'2018.02.09_11.34.09'

But then when I try to create a datetime object from this string, it doesn't work:

>>> 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'

What am I doing wrong?

1 Answer 1

6

You need to replace the format specifier %I with %M, for minutes:

%Y.%m.%d_%H.%M.%S

%I denotes hour in 12-hour format so from (0)1..12, whereas based on your example, you have 34 as the value, which presumably is in minutes (%M).

Sign up to request clarification or add additional context in comments.

2 Comments

I can't believe I did not see that mistake. Thanks and sorry for have wasted your time!
@shikhanshu It happens :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.