How to convert Python date in JSON format?


There is no standard JSON format for dates. Although JavaScript does have a standard date format that is human readable, sorts correctly, includes fractional seconds(which can help re-establish chronology) and  conforms to ISO 8601. You can convert a Python date to the JS date format using the strftime function and deserialize it using the client that needs this date. 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'. You can use it as follows −

Example

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

Updated on: 02-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements