ISO 8601 is a common date string standard that contains all the necessary information for parsing a date time. The standard is support in multiple languages, which makes it ideal for passing date information between languages. Say you want to pass a date between a Python server and JavaScript client. ISO 8601 is created for this.
In this quick tip, we will see how to format a python date to the ISO 8601 standard.
If you are using Python 3+, the iso formatting option is built in. Just call the isoformat
method on a datetime object.
from datetime import datetime
now = datetime.now()
print(now.isoformat())
If you are using Python 2, you will need to pass in the standard format using the strftime
method and the iso format string.
from datetime import datetime
now = datetime.now()
print(now.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))