📅 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!
datetime
object to string in ISO 8601 format:import datetime
= datetime.datetime.now() # Store current datetime
some_datetime_obj = some_datetime_obj.isoformat() # Convert to ISO 8601 string
datetime_str print(datetime_str) # Print the string
This prints a date string in ISO 8601 format. For example: 2019-01-23T06:17:59.273519
.
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
= "2019-01-23T06:17:59.273519" # Datestring in ISO 8601 format
datetime_str = dateutil.parser.parse(datetime_str) # Convert to datetime object some_datetime_obj