-2

I'm getting "2022-07-12T05:09:39.057266+00:00" as a string from the response, I'm not sure which format is this if its ISO 8601 or Zulu. How do I convert this into date time object?

I need to subtract this time from the current time? Any leads would be helpful.

wovano
  • 4,543
  • 5
  • 22
  • 49
Aditya Malviya
  • 1,907
  • 1
  • 20
  • 25

2 Answers2

2
from datetime import datetime

datetime.now() - datetime.fromisoformat("2022-07-12T05:09:39.057266")

For the string with a timezone, use the correct timezone for the current time ("+00:00" suggests to use UTC):

from datetime import datetime
from datetime import timezone

datetime.now(timezone.utc) - datetime.fromisoformat("2022-07-12T05:09:39.057266+00:00")
9769953
  • 10,344
  • 3
  • 26
  • 37
  • 1
    @Aditya, it's new since Python 3.7. What version do you use? Did you copy-paste the code correctly? – wovano Jul 12 '22 at 09:57
0

Use fromisoformat or the explicit format "%Y-%m-%dT%H:%M:%S.%f"

value = "2022-07-12T05:09:39.057266"

result = datetime.fromisoformat(value)
print(result)

result = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
print(result)

print(datetime.now() - result)
azro
  • 53,056
  • 7
  • 34
  • 70