How to Parse ISO 8601-formatted Date and Time in Python
Python's strptime provides a basic approach to parse RFC 3339 strings. However, for a more comprehensive solution, consider the following options:
1. isoparse Function from python-dateutil
The python-dateutil package offers the isoparse function, which can parse not only RFC 3339 strings but also other ISO 8601 formats. It supports date-only strings and extended ISO 8601 formats without UTC offsets.
import dateutil.parser dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
2. dateutil.parser.parse
Another option from the python-dateutil package is dateutil.parser.parse. While it may be less strict than isoparse, it still attempts to interpret the input string. Consider stricter methods if precision is crucial.
3. datetime.datetime.fromisoformat
Python 3.7 introduced the fromisoformat method within the datetime.datetime class. Note that its support for ISO 8601 formats is partial and varies depending on the Python version. Check its documentation for specific details.
The above is the detailed content of How to Efficiently Parse ISO 8601 Dates and Times in Python?. For more information, please follow other related articles on the PHP Chinese website!