How can I parse an ISO 8601-formatted date and time in Python date-time from isoformat? I need to parse RFC 3339 strings like “2008-09-03T20:56:35.450686Z” into Python’s datetime
type.
I have found strptime
in the Python standard library, but it is not very convenient.
What is the best way to do this?
I’ve worked with Python for a while, and one of the simplest ways to handle ISO 8601 dates is by using datetime.fromisoformat()
(Python 3.7+). It’s a straightforward, built-in method that doesn’t require any extra installations.
from datetime import datetime
iso_string = "2008-09-03T20:56:35.450686Z"
# Removing the 'Z' (Zulu time) as it's not part of the isoformat spec for fromisoformat
iso_string = iso_string.rstrip("Z")
dt = datetime.fromisoformat(iso_string)
print(dt)
This works perfectly for standard ISO 8601 strings in Python 3.7 and later.
Building on Sam’s point, if you’re dealing with a broader range of date-time formats, or even something like RFC 3339, the python-dateutil
package can save the day. Its parser.parse()
function is flexible enough to handle various ISO 8601 formats automatically.
To use it:
- Install the library:
pip install python-dateutil
- Then parse the string:
from dateutil import parser
iso_string = "2008-09-03T20:56:35.450686Z"
dt = parser.isoparse(iso_string)
print(dt)
It’s super useful when the input format can vary slightly or include ‘Z’ as a timezone indicator.
Here’s an option if you’re stuck with an older Python version (before 3.7). I’ve found that datetime.strptime()
with a custom format does the trick. It’s not as sleek as the previous methods, but it’s reliable.
from datetime import datetime
iso_string = "2008-09-03T20:56:35.450686Z"
# Stripping 'Z' to match the format string
iso_string = iso_string.rstrip("Z")
dt = datetime.strptime(iso_string, "%Y-%m-%dT%H:%M:%S.%f")
print(dt)
This works well for manually defined formats. However, note that for broader compatibility or future-proofing, consider upgrading to a more recent Python version or using python-dateutil
.