Home >Backend Development >Python Tutorial >How Can I Efficiently Parse ISO 8601 Dates and Times in Python?

How Can I Efficiently Parse ISO 8601 Dates and Times in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 09:31:11308browse

How Can I Efficiently Parse ISO 8601 Dates and Times in Python?

Parsing ISO 8601 Dates and Times with python-dateutil**

To conveniently parse ISO 8601 formatted date and time strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type, consider using the python-dateutil package's dateutil.parser.isoparse function.

isoparse Function

The isoparse function interprets various ISO 8601 date and time strings, even those that do not conform to RFC 3339 specifications (e.g., strings without UTC offsets or date-only strings).

Usage:

>>> 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)

Alternatives to isoparse**

The python-dateutil package also provides dateutil.parser.parse, which is less strict and may attempt interpretations. For maximum accuracy, consider using a stricter parser.

Caution with Python's Built-in datetime.datetime.fromisoformat**

In Python versions prior to 3.10, fromisoformat is not a complete ISO-8601 parser. In Python 3.11, it almost fully supports ISO 8601, but maintains some limitations. Consult the official documentation for specific details.

The above is the detailed content of How Can I Efficiently Parse ISO 8601 Dates and Times in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn