0

what is wrong with my FMT formatting for datetime? My date is formatted as follows:

mytime = '2021-12-06T13:52:41.864+0000'

I am trying to parse it with

FMT = '%Y-%m-%dT%H:%M:%S.%f+%Z'

and

FMT = '%Y-%m-%dT%H:%M:%S.%f+0000'

To be able to do:

datetime.strptime(mytime, FMT)

Both my solutions do not work. Any idea?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Kelly o'Brian
  • 415
  • 3
  • 12
  • Do you get an error, or it just isn't the result you are expecting? Also, how are you importing `datetime` ? – jkoestinger Mar 17 '22 at 12:47
  • see also [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Mar 17 '22 at 12:53

2 Answers2

2

remove + and use z instead of Z.

from datetime import datetime

mytime = '2021-12-06T13:52:41.864+0000'
datetime.strptime(mytime, '%Y-%m-%dT%H:%M:%S.%f%z')

output:

datetime.datetime(2021, 12, 6, 13, 52, 41, 864000, tzinfo=datetime.timezone.utc)
JayPeerachai
  • 3,499
  • 3
  • 14
  • 29
0

You're using the wrong timezone directive in your FMT, use %z, not +%Z.

%z: UTC offset in the form +HHMM or -HHMM.

fannheyward
  • 18,599
  • 12
  • 71
  • 109