简体   繁体   English

如何验证字符串是 RFC3339 格式的时间?

[英]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.我有以下字符串'2012-10-09T19:00:55Z'并且我想验证它是否采用RFC3339时间格式。

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 .这里的问题是,这会返回一个非时区感知 object ,正如此处指出的那样。

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.这确保日期时间 object 是时区感知的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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