When working with date and time data in your Python applications, especially from APIs, databases, or event logs, you will encounter ISO 8601-formatted strings. There are standard measures, formats that are internationally accepted and easy for both users and machines to interpret. Parsing these formats would allow you to convert them into the datetime format, which you can use to manipulate and compare the data based on your needs. In this blog, you will explore several ways to parse ISO 8601 in Python in detail with examples.
Table of Contents:
The ISO 8601 format is a globally accepted standard for representing date and time. This will remove ambiguity by keeping consistency in the structure to express data. For example, in a case when an ISO8601 date string like 2025-04-10T15:45:30+00:00 carries all the important parts or components to describe time, date, timezone offset. The date part also has a subformat appearing as year-month-day, which is separated by hyphens. The character T separates the date and time. The time is represented in 24-hour format, and it may optionally include a timezone suffix like Z for UTC or an offset such as +05:30. This formatting is preferred in data exchange because it is easy to parse and sort chronologically.
Why Do We Have to Parse ISO 8601 Dates in Python?
Parsing ISO 8601 date strings in Python is essential when you receive date-time information as plain text but want to perform operations like comparison, subtraction, formatting, or timezone conversion. You probably have worked with APIs that return timestamps in ISO 8601 format, or there might be scenarios where logging events in your app require serializing and deserializing timestamps effectively. In such cases, we can convert ISO 8601 strings to datetime objects to give us better control over the program, allowing us to build features. Features like time-based filters, scheduled tasks, reports, and certain visualisations. If you don’t perform parsing, you would be stuck with strings that are difficult to manipulate and get a meaning out of them.
Methods to Parse ISO 8601 in Python
Python provides several built-in and third-party ways to parse ISO 8601 strings.
One of the simplest methods to work on is the datetime.fromisoformat() method, available from Python version 3.7 and onwards. This function parses date strings that strictly follow the ISO format, including those with or without time components.
Example:
Output:
Explanation: In the example above, the ISO string “2025-04-10T15:45:30” is parsed into a Python datetime object using fromisoformat(). This method works well for ISO 8601 strings, including those with or without timezone offsets (like +05:30) or the Z suffix for UTC. The result is a datetime object that you can use for further operations like time arithmetic or comparisons.
Using dateutil.parser.parse() in Python
If you want to work with more flexibility, dateutil.parser.parse() is a powerful choice. It can interpret a broad variety of ISO 8601 formats, including those with offsets and subsecond precision.
Example:
Output:
Explanation: Here, the dateutil library has the parse function that interprets the ISO 8601 string with a timezone offset like +05:30. This would return a datetime object that is aware of the timezone. Such an output is useful when the input format varies from time to time or you have to deal with multiple time zones in your application.
Using datetime.strptime() in Python
You can also use datetime.strptime() if the format is known and consistent. This method allows you to define a custom format and parse accordingly.
Example:
Output:
Explanation: Here, the function strptime() is implemented to provide a matching format string: “%Y-%m-%dT%H:%M:%S” by manually parsing the ISO 8601 string. This will work best if your input is consistent, but it is less forgiving when the format does not match, and it will raise an error.
Using Pendulum in Python
The pendulum library provides both ease of use and advanced timezone support. Here’s how you’d use it.
Example:
Output:
Explanation: Here, the parse() function of pendulum handles ISO 8601 strings effortlessly and gives back a Datetime object with built-in timezone support. The object here is much more powerful than the standard datetime module. This will offer you direct methods for time formatting, time shifting, etc.
Comparison Table of Each Method
Method | Timezone Support | Flexibility with Formats | Performance |
fromisoformat() | limited | Standard ISO only | Fast and best for simple, trusted formats |
dateutil.parser.parse() | Has timezone coverage | Very flexible | Moderate and best for varied real-world input |
strptime() | Doesn’t have timezone coverage | Needs exact information | Fast and best for varied real-world input |
pendulum.parse() | Has timezone coverage | Flexible, with time zone support | Fast and efficient, Ideal for timezone-aware apps |
Real-world Examples
The below section provides you with two sample cases for real-world application.
1. Timestamp for fetching audit logs from an API
In your day-to-day coding, parsing ISO 8601 is a practical approach for certain development projects. Let us assume you’re working on a backend service that fetches audit logs from an API. Each log has a timestamp like “2025-04-10T21:15:00Z”. You would have to convert strings to datetime objects before you can filter or compare logs.
Example:
Output:
Explanation: Here you’re parsing the ISO 8601 timestamp into a timezone-aware datetime object that you can use for filtering or formatting in your logs or UI.
2. Timestamp to build a report feature
In another scenario, let us assume you’re building a report feature that calculates how long a task or campaign lasted. The timestamps are in ISO format
Example:
Output:
Explanation: Here, the example shows us how we can calculate a duration using ISO 8601 timestamps. The start and end times are parsed into datetime objects utilising fromisoformat(). When you subtract these objects, you will get a timedelta, giving you the total duration.
Best Practices
- Keep in mind to utilise parsing that is time-zone sensitive: When working across regions, time zones tend to drastically affect results in such a case.
- It is always better to validate your input before parsing: You can catch exceptions like ValueError or ParseError exceptions, so that you can effectively avoid crashing your app because of inputs that were malformed.
- Stick to UTC internally to maintain consistency: It is best practice to standardize your UTC. This will make storing, sorting, and creating comparisons between timestamps more predictable.
- Best to avoid mixing naive and aware datetime objects: Operations between these two types can bring exceptions or silently produce incorrect results.
- Date formats in APIs and internal tools need to be documented: You can get help to reduce parsing errors, if you have clarity in format, it does not matter if you are producing or consuming dates.
Conclusion
In Python, parsing ISO 8601-formatted date and time strings is very important when working with any system that involves timestamped data. ISO dates ensure that your application runs smoothly as predicted. You are now aware of different formats using built-in methods present in Python, like fromisoformat() and strptime(). You were also showcased third-party alternatives like dateutil and pendulum, choosing the perfect method depends on your case. Controlled formats use built-in methods, while variable or format-sensitive to time zones benefit from external libraries.
Further, check out our Python certification course and get ready to excel in your career with our Basic Python interview questions prepared by experts.
How to Parse ISO 8601 Date and Time in Python – FAQs
Q1. What does the Z mean in ISO 8601?
In this instance, Z indicates that the time is in UTC (Zulu Time), which is equivalent to a timezone offset of +00:00.
Q2. Can ISO 8601 dates include milliseconds?
Yes, and most parsers like dateutil and pendulum can handle microsecond precision automatically.
Q3. Why does the method strptime() fail on some ISO 8601 strings?
It fails because it requires an exact format string and does not support timezone parsing out of the box.
Q4. Should I consider using naive or aware datetimes in my app?
Use datetimes that are aware of timezones when you require accurate calculations for time-zones, or use naive datetimes are fine for local-only operations.
Q5. Can I convert an ISO 8601 string directly into UTC?
Yes, when you parse the ISO 8601 string into a datetime object, you should be able to convert it to UTC using the .astimezone(timezone.utc) method.