How to Create a JSON Timestamp Converter in Python?

Estimated read time 2 min read

Creating a JSON timestamp converter in Python involves using the json module to load and dump JSON data, and the datetime module to work with timestamps. Here’s an example of how you can create a JSON timestamp converter:

import json
import datetime

# Define a custom JSON encoder to handle datetime objects
class TimestampEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            # Convert datetime objects to ISO format
            return obj.isoformat()
        return super(TimestampEncoder, self).default(obj)

# Define a custom JSON decoder to handle datetime objects
def datetime_decoder(obj):
    if isinstance(obj, str):
        try:
            # Convert ISO format string to datetime objects
            return datetime.datetime.fromisoformat(obj)
        except ValueError:
            pass
    return obj

# Example usage

# Create a dictionary with a datetime object
data = {
    "name": "John",
    "age": 30,
    "timestamp": datetime.datetime.now()
}

# Serialize the dictionary to JSON with custom encoder
json_string = json.dumps(data, cls=TimestampEncoder)
print("Serialized JSON:", json_string)

# Deserialize the JSON to dictionary with custom decoder
loaded_data = json.loads(json_string, object_hook=datetime_decoder)
print("Loaded data

In the above example, a custom JSON encoder TimestampEncoder is defined to handle datetime objects by converting them to ISO format using the isoformat() method. The default() method is overridden to provide custom serialization behavior for datetime objects.

Similarly, a custom JSON decoder datetime_decoder is defined to handle datetime objects by converting ISO format strings to datetime objects using the fromisoformat() method.

You can use these custom encoder and decoder when serializing and deserializing JSON data in your Python code to properly handle datetime objects as timestamps.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply