如何解析ISO 8601格式的日期?

我须要将RFC 3339字符串(如"2008-09-03T20:56:35.450686Z"解析为Python的datetime类型。 python

我在Python标准库中找到了strptime ,但这不是很方便。 git

作这个的最好方式是什么? github


#1楼

您获得的确切错误是什么? 像下面吗? 测试

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

若是是,则能够在“。”上分割输入字符串,而后将微秒添加到得到的日期时间。 spa

尝试这个: code

>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

#2楼

import re,datetime
s="2008-09-03T20:56:35.450686Z"
d=datetime.datetime(*map(int, re.split('[^\d]', s)[:-1]))

#3楼

尝试使用iso8601模块; 它正是这样作的。 orm

python.org Wiki上的WorkingWithTime页面上提到了其余几个选项。 ip


#4楼

请注意,在Python 2.6+和Py3K中,%f字符捕获微秒。 字符串

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

在这里查看问题 get


#5楼

我已经为ISO 8601标准编写了一个解析器,并将其放在GitHub上: https : //github.com/boxed/iso8601 。 此实现支持规范中的全部内容,但持续时间,间隔,周期性间隔和日期不在Python datetime模块支持的日期范围内。

测试包括在内! :P

相关文章
相关标签/搜索