How to convert datetime to and from ISO 8601 string

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!

  • Convert a datetime object to string in ISO 8601 format:
import datetime
some_datetime_obj = datetime.datetime.now()  # 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.

  • To convert a ISO 8601 format string to datetime object we need a package named dateutil. This is available as python-dateutil and python3-dateutil in Ubuntu or dateutil as PIP package. Once this package is installed, you can do:
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
Advertisements

3 thoughts on “How to convert datetime to and from ISO 8601 string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.