1

I have the following string '2012-10-09T19:00:55Z' and I want to verify it's in RFC3339 time format.

One (wrong) approach would be to do something like the following:

datetime.strptime('2012-10-09T19:00:55Z', '%Y-%m-%dT%H:%M:%S.%fZ')

The issue here is that this return a non time zone aware object as pointed out here.

Any idea how can I achieve this?

Newskooler
  • 3,973
  • 7
  • 46
  • 84

1 Answers1

2

I found this solution:

from datetime import datetime

assert datetime.strptime('2012-10-09T19:00:55Z', '%Y-%m-%dT%H:%M:%S%z')
assert datetime.strptime('2012-10-09T19:00:55Z', '%Y-%m-%dT%H:%M:%S%z').tzinfo is not None

Notice the subtle difference in the string format. This makes sure that the datetime object is time zone aware.

Newskooler
  • 3,973
  • 7
  • 46
  • 84
  • related: https://stackoverflow.com/questions/522251/whats-the-difference-between-iso-8601-and-rfc-3339-date-formats/522281#522281 - I think your format code is a bit strict ;-) Maybe a `regex` would be a cleaner way to *verify* the string's compliance with RFC3339? – FObersteiner Jul 07 '20 at 06:19
  • Thanks, I will look into this. – Newskooler Jul 07 '20 at 13:08