How to convert Python date in JSON format?

There is no standard JSON format for dates. However, the ISO 8601 format is widely accepted as it's human readable, sorts correctly, includes fractional seconds, and is compatible with most programming languages. Python provides several methods to convert dates to JSON-compatible ISO format.

Using isoformat() Method

The isoformat() method is the simplest way to convert a Python datetime object to ISO 8601 format ?

from datetime import datetime

my_date = datetime.now()
print(my_date.isoformat())
2018-01-02T22:08:12.510696

Using strftime() Method

For more control over the output format, you can use the strftime() function with custom format specifiers ?

from datetime import datetime

my_date = datetime.now()
print(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f'))
2018-01-02T22:10:05.284208

Converting to JSON with Custom Encoder

When serializing datetime objects directly to JSON, you need a custom encoder to handle the conversion ?

import json
from datetime import datetime

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

data = {
    'name': 'John',
    'created_at': datetime.now()
}

json_string = json.dumps(data, cls=DateTimeEncoder)
print(json_string)
{"name": "John", "created_at": "2018-01-02T22:12:15.123456"}

Comparison of Methods

Method Output Format Best For
isoformat() ISO 8601 standard Simple date conversion
strftime() Custom format Specific formatting needs
Custom Encoder JSON serialization Complex objects with dates

Conclusion

Use isoformat() for simple ISO 8601 conversion, strftime() for custom formatting, and custom JSON encoders when serializing complex objects containing datetime fields.

Updated on: 2026-03-24T19:30:19+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements