Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下字符串'2012-10-09T19:00:55Z',我想验证它的RFC3339时间格式。
'2012-10-09T19:00:55Z'
RFC3339
一种(错误的)方法是执行以下操作:
datetime.strptime('2012-10-09T19:00:55Z', '%Y-%m-%dT%H:%M:%S.%fZ')
这里的问题是,这会返回一个非时区感知对象,如此处所指出的。
知道如何实现这一目标吗?
我找到了这个解决方案:
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
注意字符串格式的细微差别。这确保了 datetime 对象是时区感知的。