如何解析ISO 8601格式的日期? [英] How to parse an ISO 8601-formatted date?
问题描述
我需要解析 RFC 3339 字符串,如2008-09 -03T20:56:35.450686Z
到Python的 datetime
类型。
发现 strptime
在Python标准库中,但它不是很方便。
最好的方法是什么?
python-dateutil 包不仅可以解析问题中的RFC 3339 datetime字符串,还可以解析其他ISO 8601日期和时间字符串这不符合RFC 3339(如没有UTC偏移量或仅代表日期的那些)。
>>> import dateutil.parser
$请注意,
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z')#RFC 3339格式
datetime.datetime(2008,9,3,20,56,35,450686,tzinfo = tzutc() )
>>> dateutil.parser.parse('2008-09-03T20:56:35.450686')#ISO 8601扩展格式
datetime.datetime(2008,9,3,20,56,35,450686)
> ;>> dateutil.parser.parse('20080903T205635.450686')#ISO 8601基本格式
datetime.datetime(2008,9,3,20,56,35,450686)
>>> dateutil.parser.parse('20080903')#ISO 8601基本格式,仅限日期
datetime.datetime(2008,9,3,0,0)
dateutil.parser
是有意骇人听闻的:p $ p>
它试图猜测格式,并在不明确的情况下做出不可避免的假设(可手动定制)。所以只有在需要解析未知格式的输入时才可以使用它,并且可以容忍偶尔的误读。 (感谢 ivan_pozdeev )
Pypi名称为< a href =https://pypi.python.org/pypi/python-dateutil>
python-dateutil
,而不是dateutil
(感谢 code3monk3y ):pip install python-dateutil
I need to parse RFC 3339 strings like
"2008-09-03T20:56:35.450686Z"
into Python'sdatetime
type.I have found
strptime
in the Python standard library, but it is not very convenient.What is the best way to do this?
解决方案The python-dateutil package can parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).
>>> import dateutil.parser >>> dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc()) >>> dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format datetime.datetime(2008, 9, 3, 20, 56, 35, 450686) >>> dateutil.parser.parse('20080903') # ISO 8601 basic format, date only datetime.datetime(2008, 9, 3, 0, 0)
Be warned that the
dateutil.parser
is intentionally hacky: it tries to guess the format and makes inevitable assumptions (customizable by hand only) in ambiguous cases. So ONLY use it if you need to parse input of unknown format and are okay to tolerate occasional misreads. (thanks ivan_pozdeev)The Pypi name is
python-dateutil
, notdateutil
(thanks code3monk3y):pip install python-dateutil
这篇关于如何解析ISO 8601格式的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!