如何解析ISO 8601格式的日期? [英] How do I parse an ISO 8601-formatted date?

查看:434
本文介绍了如何解析ISO 8601格式的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将"2008-09-03T20:56:35.450686Z"之类的 RFC 3339 字符串解析为Python的datetime类型.

I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type.

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

I have found strptime in the Python standard library, but it is not very convenient.

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

python-dateutil 包不仅可以解析RFC 3339日期时间字符串,例如问题中的字符串,还可以解析其他 ISO 8601 不符合RFC 3339的日期和时间字符串(例如不具有UTC偏移量的字符串或那些只代表一个日期).

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.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)


请注意, dateutil.parser.isoparse 可能更严格比起 dateutil.parser.parse 更加狡猾,但两者它们非常宽容,并且会尝试解释您传入的字符串.如果要消除任何误读的可能性,则需要使用比这两个函数中的任何一个都严格的内容.


Note that dateutil.parser.isoparse is presumably stricter than the more hacky dateutil.parser.parse, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions.

Pypi名称为 python-dateutil ,而不是dateutil(感谢 code3monk3y ):

The Pypi name is python-dateutil, not dateutil (thanks code3monk3y):

pip install python-dateutil

如果您使用的是Python 3.7,请查看关于datetime.datetime.fromisoformat此答案.

If you're using Python 3.7, have a look at this answer about datetime.datetime.fromisoformat.

这篇关于如何解析ISO 8601格式的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆