Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading