如何将ISO 8601日期时间字符串转换为Python日期时间对象?

2024-04-26 06:52:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个日期时间字符串,格式类似于“2009-05-28T16:15:00”(我相信这是ISO 8601)。有一个骇人听闻的选项似乎是使用time.strptime解析字符串,并将元组的前六个元素传递给datetime构造函数,如:

datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])

我找不到一个更干净的方法来做这件事。有吗?


Tags: 方法字符串元素datetimetime格式选项时间
3条回答

我更喜欢使用dateutil库进行时区处理和一般的固体日期解析。如果你要得到一个ISO 8601字符串,比如:2010-05-08T23:41:54.000Z,你会很高兴用strtime解析它,特别是如果你不知道是否包含时区。pyiso8601有几个问题(检查他们的跟踪器)是我在使用过程中遇到的,而且已经有几年没有更新了。相比之下,dateutil一直在为我工作:

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

由于Python 3.7没有外部库:

datetime.datetime.strptime('2019-01-04T16:41:24+0200', "%Y-%m-%dT%H:%M:%S%z")

Python 2不支持%z格式说明符,因此最好尽可能在任何地方显式使用Zulu时间:

datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")

因为ISO 8601允许存在许多可选冒号和破折号的变体,所以基本上是CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]。如果你想使用strtime,你需要先去掉那些变体。

目标是生成一个UTC日期时间对象。


如果您只需要一个对UTC有效的Z后缀的基本案例,比如2016-06-29T19:36:29.3453Z

datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")

如果要处理诸如2016-06-29T19:36:29.3453-04002008-09-03T20:56:35.450686+05:00之类的时区偏移,请使用以下命令。这些函数将把所有变量转换成不带变量分隔符的变量,比如20080903T205635.450686+0500,使其更一致/更易于解析。

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构建类型(即JythonCython等)中各不相同。

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

相关问题 更多 >