1

How can I convert '2021-11-21T18:57:18.000+01:00' from json to datetime in Python?

  timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")

is giving me error:

ValueError: time data '2021-11-21T18:57:18.000+01:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    Python 3.7+: use [fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat), it is [more efficient](https://stackoverflow.com/q/13468126/10197418). – FObersteiner Nov 21 '21 at 19:38

1 Answers1

1

Your formatting string is slightly wrong. You need %z to parse the zone offset:

from datetime import datetime

timestamp = '2021-11-21T18:57:18.000+01:00'
timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")

print(timestamp)

Result:

2021-11-21 18:57:18+01:00
rdas
  • 20,604
  • 6
  • 33
  • 46