[英]Checking if a date string is in UTC format
I have a date string like "2011-11-06 14:00:00+00:00".我有一个日期字符串,例如“2011-11-06 14:00:00+00:00”。 Is there a way to check if this is in UTC format or not?.
有没有办法检查这是否是UTC格式? I tried to convert the above string to a datetime object using
utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z)
so that i can compare it with pytz.utc, but i get 'ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M%S+%z'我尝试使用
utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z)
将上述字符串转换为日期时间 object utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z)
以便我可以将其与 pytz.utc 进行比较,但我得到 'ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M%S+%z'
How to check if the date string is in UTC?.如何检查日期字符串是否为 UTC? Some example would be really appreciated.
一些例子将不胜感激。
Thank You谢谢你
A simple regular expression will do:一个简单的正则表达式就可以了:
>>> import re
>>> RE = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$')
>>> bool(RE.search('2011-11-06 14:00:00+00:00'))
True
The problem with your format string is that strptime
just passes the job of parsing time strings on to c's strptime
, and different flavors of c accept different directives.您的格式字符串的问题在于
strptime
只是将解析时间字符串的工作传递给 c 的strptime
,并且不同风格的 c 接受不同的指令。 In your case (and mine, it seems), the %z
directive is not accepted.在您的情况下(似乎是我的情况),不接受
%z
指令。
There's some ambiguity in the doc pages about this.文档页面中对此存在一些歧义。 The
datetime.datetime.strptime
docs point to the format specification for time.strptime
which doesn't contain a lower-case %z
directive, and indicates thatdatetime.datetime.strptime
文档指向time.strptime
的格式规范,它不包含小写的%z
指令,并表明
Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C.
某些平台可能支持其他指令,但只有此处列出的指令具有由 ANSI C 标准化的含义。
But then it also points here which does contain a lower-case %z
, but reiterates that但它也指出这里确实包含小写
%z
,但重申
The full set of format codes supported varies across platforms, because Python calls the platform C library's strftime() function, and platform variations are common.
支持的全套格式代码因平台而异,因为 Python 调用平台 C 库的 strftime() function 和平台变化是常见的。
There's also a bug report about this issue.还有一个关于这个问题的错误报告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.