Python – using strptime() to convert "20:52:30.0000000+02:00" into datetime

Question:

I’m trying to do something like this this:

time_str = "20:52:30.0000000+02:00"
time = datetime.strptime(time_str, "%H:%M:%S.%f%z")

But I’m getting the following error ValueError: time data '20:52:30.0000000+02:00' does not match format '%H:%M:%S.%f%z'. It’s obvious that my format string is wrong, but I’ve gone through many stackoverflow threads while trying to find the correct one to no avail.

Is direct conversion even possible with the current input string format?

Thanks in advance

EDIT:
As people mentioned in the comments, the timezone should be written as 0200 instead of 02:00. But if I change my code accordingly, I still get the same error:

time_str = "20:52:30.0000000+0200"
time = datetime.strptime(time_str, "%H:%M:%S.%f%z")

ValueError: time data '20:52:30.0000000+0200' does not match format '%H:%M:%S.%f%z'

You can try it here in online interpreter https://www.online-python.com/NXw90TtQJ8

Asked By: stitch123

||

Answers:

%f handles values in range: 000000 – 999999 (https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
Remove one zero from input string and your code should work

from datetime import datetime

time_str = "20:52:30.000000+0200"
time = datetime.strptime(time_str, "%H:%M:%S.%f%z")

Another way to do this is to add %w to strptime:

from datetime import datetime

time_str = "20:52:30.0000000+0200"
time = datetime.strptime(time_str, "%H:%M:%S.%w%f%z")

However, using %-variables changes the fields of an object time that is being created with strptime function.

In that case the last six numbers from "20:52:30.0[000000]+0200" would be used to set microseconds field, which you probably won’t use.

Nevertheless, ask someone from whom you get the data to give you an explanation of the format the data has.

Answered By: mlokos
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.