Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to convert datetime to and from ISO 8601 string

📅 2017-Oct-12 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ datetime, dateutil, iso 8601, python ⬩ 📚 Archive

ISO 8601 is a standardized format for representing date and time that is popular. Python has built-in support to convert to and from this format. But confusingly, those methods are distributed across two different modules!

import datetime
some_datetime_obj =  # Store current datetime
datetime_str = some_datetime_obj.isoformat()  # Convert to ISO 8601 string
print(datetime_str)  # Print the string

This prints a date string in ISO 8601 format. For example: 2019-01-23T06:17:59.273519.

import dateutil.parser
datetime_str = "2019-01-23T06:17:59.273519"  # Datestring in ISO 8601 format
some_datetime_obj = dateutil.parser.parse(datetime_str)  # Convert to datetime object