Search code examples
pythondatevalidationtimezonerfc3339

How to validate that a string is a time in RFC3339 format?


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?


Solution

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