[英]Date with a time zone specified as a string is parsed as naive
I'm curious why the timezone in this example, GMT
, is not parsed as a valid one:我很好奇为什么这个例子中的时区
GMT
没有被解析为有效的时区:
>>> from datetime import datetime
>>> import pytz
>>> b = 'Mon, 3 Oct 2016 21:24:17 GMT'
>>> fmt = '%a, %d %b %Y %H:%M:%S %Z'
>>> datetime.strptime(b, fmt).astimezone(pytz.utc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
Doing the same with a -0700
instead of GMT
and %z
instead of %Z
in the format works just fine.在格式中使用
-0700
而不是GMT
和%z
而不是%Z
做同样的-0700
就可以了。
What's the proper way to parse dates ending in string time zones if not this?如果不是这样,解析以字符串时区结尾的日期的正确方法是什么?
Use .replace()
method with datetime
object to update the time zone info.使用
.replace()
方法和datetime
对象来更新时区信息。
>>> datetime.strptime(b, fmt).replace(tzinfo=pytz.utc)
datetime.datetime(2016, 10, 3, 21, 24, 17, tzinfo=<UTC>)
Since you mentioned, .astimezone()
is working with %Z
instead of %s
in the format string.既然你提到了,
.astimezone()
在格式字符串中使用%Z
而不是%s
。 Even though there is z
in both the formatting (difference in just case), but they are totally different in terms of what they represent.尽管两种格式中都有
z
(只是情况不同),但它们所代表的内容完全不同。
As per the strftime
's directive document:根据
strftime
的指令文件:
%z : UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).
%z :格式为 +HHMM 或 -HHMM 的 UTC 偏移量(如果对象是幼稚的,则为空字符串)。
%Z : Time zone name (empty string if the object is naive).
%Z :时区名称(如果对象是幼稚的,则为空字符串)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.