Home >Backend Development >Python Tutorial >How to Easily Parse ISO 8601 Dates and Times in Python?

How to Easily Parse ISO 8601 Dates and Times in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 21:37:12547browse

How to Easily Parse ISO 8601 Dates and Times in Python?

How to Parse an ISO 8601-Formatted Date and Time in Python

Python's strptime function is not ideal for parsing ISO 8601-formatted date and time strings. For a more convenient solution, consider the isoparse function from the python-dateutil package.

isoparse Function

isoparse is designed specifically to parse ISO 8601 datetime strings like "2008-09-03T20:56:35.450686Z". It also handles other ISO 8601 date and time formats, such as those without UTC offset or representing only a date.

import dateutil.parser
datetime_object = dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z')

Comparison with Python's datetime.datetime.fromisoformat

In Python 3.7 and earlier, datetime.datetime.fromisoformat is not a complete ISO 8601 format parser. It only supports a subset of valid ISO 8601 formats. In Python 3.11, fromisoformat supports almost all valid ISO 8601 strings.

Handling Misreads

isoparse and other lenient parsers can potentially misread certain strings. For more strict parsing, consider using a different library or implementing your own parsing logic.

Conclusion

The isoparse function from python-dateutil provides a convenient and comprehensive way to parse ISO 8601-formatted date and time strings in Python. It supports a wide range of formats and handles UTC offsets correctly.

The above is the detailed content of How to Easily 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