简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM