我得到了一个格式为“2009-05-28T16:15:00”的日期时间字符串(我相信这是ISO 8601)。一个比较黑的选项似乎是使用时间来解析字符串。Strptime并将元组的前六个元素传递给datetime构造函数,例如:

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

我还没有找到一种“更干净”的方式来做这件事。有吗?


当前回答

因为ISO 8601允许出现多种可选冒号和破折号,基本上是CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]。如果希望使用strptime,则需要先去掉这些变量。

目标是生成一个UTC datetime对象。


如果你只想要一个适用于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-0400或2008-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" )

如果您的系统不支持%z strptime指令(您会看到类似ValueError: 'z'是一个格式为'%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

其他回答

import datetime, time
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
    dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds

这还包括毫秒和时区。

如果时间是'2012-09-30T15:31:50.262-08:00',这将转换为纪元时间。

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

我更喜欢使用dateutil库进行时区处理和通常可靠的日期解析。如果您要得到一个ISO 8601字符串,例如:2010-05-08T23:41:54.000Z,那么使用strptime解析它会很有趣,特别是如果您事先不知道是否包含时区。pyiso8601有几个问题(检查他们的跟踪器),我在使用过程中遇到了,它已经几年没有更新了。相比之下,Dateutil一直很活跃,对我来说很有效:

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

因为ISO 8601允许出现多种可选冒号和破折号,基本上是CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]。如果希望使用strptime,则需要先去掉这些变量。

目标是生成一个UTC datetime对象。


如果你只想要一个适用于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-0400或2008-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" )

如果您的系统不支持%z strptime指令(您会看到类似ValueError: 'z'是一个格式为'%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

我还没有尝试过,但是pyiso8601承诺支持这一点。

Isodate似乎有最完整的支持。