2

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

stitch123
  • 197
  • 9
  • TIme Zone is of the form HHMM, so 0200 instead of 02:00. (inside `time_str`) – Naitik Mundra Oct 23 '22 at 19:35
  • @NaitikMundra Removing the last colon from `time_str` seems to raise the same error about the format being wrong. Here's the code in an online editor https://www.online-python.com/NXw90TtQJ8 – stitch123 Oct 23 '22 at 19:40
  • 1
    https://stackoverflow.com/questions/56360908/how-can-i-use-datetime-strptime-on-a-string-in-the-format-0000-00-00t0000000 – mlokos Oct 23 '22 at 19:43
  • This suggests that timezone should be 0200 instead of 02:00, just like @NaitikMundra said, but when I remove the colon, I get the same error. I'll edit the original post accordingly. – stitch123 Oct 23 '22 at 19:47

1 Answers1

2

%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.

mlokos
  • 359
  • 2
  • 10
  • %w will work better in my case, thank you. I pull these time strings from a source which I have no control of, so this way I won't have to edit them as much before converting them into datetime. – stitch123 Oct 23 '22 at 19:59