Computer >> Computer tutorials >  >> Programming >> Python

How do I get an ISO 8601 date in string format in Python?


To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'. 

Example

You can use it as follows −

from datetime import datetime
my_date = datetime.now()
print(my_date.isoformat())

Output

This will give the output −

2018-01-02T22:08:12.510696

In older python versions, you can use the strftime function to format the datetime object such that you get the desired result. 

example

from datetime import datetime
my_date = datetime.now()
print(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))

Output

This will give the output −

2018-01-02T22:10:05.284208