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
>Solution :
%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")