如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象?[重复]
- 2024-12-13 08:36:00
- admin 原创
- 155
问题描述:
我得到了一个日期时间字符串,格式类似于“2009-05-28T16:15:00”(我相信这是 ISO 8601)。一个 hackish 选项似乎是使用time.strptime
元组的前六个元素解析字符串并将其传递到日期时间构造函数中,例如:
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
我还没能找到一种“更干净”的方法来做这件事。有吗?
解决方案 1:
我更喜欢使用dateutil库进行时区处理和一般可靠的日期解析。如果您要获得ISO 8601
如下字符串:2010-05-08T23:41:54.000Z
使用 strptime 解析它会很有趣,特别是如果您事先不知道是否包含时区。pyiso8601
在使用过程中遇到了几个问题(检查其跟踪器),并且几年都没有更新。相比之下,dateutil 一直很活跃并且对我有用:
from dateutil import parser
yourdate = parser.parse(datestring)
解决方案 2:
从 Python 3.7 开始,没有外部库,你可以使用模块fromisoformat
中的函数datetime
:
datetime.datetime.fromisoformat('2019-01-04T16:41:24+02:00')
Python 2 不支持%z
格式说明符,因此最好尽可能在任何地方明确使用祖鲁时间:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
解决方案 3:
因为 ISO 8601 允许存在多种可选冒号和破折号的变体,所以基本上CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
。如果您想使用 strptime,则需要先删除这些变体。
目标是生成一个 UTC 日期时间对象。
如果您只想要一个适用于带有 Z 后缀的 UTC 的基本情况,例如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' 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
解决方案 4:
Arrow看起来很有希望实现这一点:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow 是一个 Python 库,它提供了一种合理、智能的方式来创建、操作、格式化和转换日期和时间。Arrow 简单、轻量,深受moment.js和请求的启发。
解决方案 5:
您应该留意时区信息,因为在比较非 tz 感知日期时间与 tz 感知日期时间时可能会遇到麻烦。
最好总是让它们了解 tz(即使只是 UTC),除非你真的知道为什么这样做没有任何用处。
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
if not when:
when = datetime.datetime.now(tz)
if not when.tzinfo:
when = tz.localize(when)
_when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
_when = dateutil.parser.parse(when)
if not _when.tzinfo:
_when = tz.localize(_when)
return _when
#-----------------------------------------------
解决方案 6:
我还没有尝试过,但是pyiso8601承诺支持这一点。
解决方案 7:
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')+\n 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
解决方案 8:
两种方式:
纪元至 ISO 时间:
isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))
ISO 时间至纪元:
epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))
解决方案 9:
Isodate似乎有最完整的支持。
解决方案 10:
aniso8601应该可以处理这个问题。它还理解时区、Python 2 和 Python 3,并且对ISO 8601的其余部分有合理的覆盖范围,如果你需要的话。
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
解决方案 11:
这是进行此类转换的一种非常简单的方法。无需解析或额外的库。它简洁、简单且快速。
import datetime
import time
################################################
#
# Takes the time (in seconds),
# and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################
def TimeToISO8601(seconds):
strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
strKv = strKv + "T"
strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
strKv = strKv +"Z"
return strKv
################################################
#
# Takes a string of the time in ISO8601 format,
# and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################
def ISO8601ToTime(strISOTime):
K1 = 0
K2 = 9999999999
K3 = 0
counter = 0
while counter < 95:
K3 = (K1 + K2) / 2
strK4 = TimeToISO8601(K3)
if strK4 < strISOTime:
K1 = K3
if strK4 > strISOTime:
K2 = K3
counter = counter + 1
return K3
################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
# and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################
def ISO8601ToDateTime(strISOTime):
return time.gmtime(ISO8601ToTime(strISOTime))
#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))
扫码咨询,免费领取项目管理大礼包!