import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
如果您的系统不支持%zstrtime指令(您可以看到类似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'的指令),则需要手动从Z(UTC)偏移时间。注意%z在Python版本中可能不适用于您的系统<;3,因为它取决于C库支持,而C库支持在系统/Python构建类型(即Jython、Cython等)中各不相同。
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
我更喜欢使用dateutil库进行时区处理和一般的固体日期解析。如果你要得到一个ISO 8601字符串,比如:2010-05-08T23:41:54.000Z,你会很高兴用strtime解析它,特别是如果你不知道是否包含时区。pyiso8601有几个问题(检查他们的跟踪器)是我在使用过程中遇到的,而且已经有几年没有更新了。相比之下,dateutil一直在为我工作:
由于Python 3.7没有外部库:
Python 2不支持
%z
格式说明符,因此最好尽可能在任何地方显式使用Zulu时间:因为ISO 8601允许存在许多可选冒号和破折号的变体,所以基本上是
CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
。如果你想使用strtime,你需要先去掉那些变体。目标是生成一个UTC日期时间对象。
如果您只需要一个对UTC有效的Z后缀的基本案例,比如
2016-06-29T19:36:29.3453Z
:如果要处理诸如
2016-06-29T19:36:29.3453-0400
或2008-09-03T20:56:35.450686+05:00
之类的时区偏移,请使用以下命令。这些函数将把所有变量转换成不带变量分隔符的变量,比如20080903T205635.450686+0500
,使其更一致/更易于解析。如果您的系统不支持
%z
strtime指令(您可以看到类似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
的指令),则需要手动从Z
(UTC)偏移时间。注意%z
在Python版本中可能不适用于您的系统<;3,因为它取决于C库支持,而C库支持在系统/Python构建类型(即Jython、Cython等)中各不相同。相关问题 更多 >
编程相关推荐