Michelle Santos
Michelle Santos

Reputation: 267

How to convert the timestamp inside a JSON file format using Python

I'm a newbie in creating Python Lambda function and I'm trying to figure out how to convert all the timestamps inside my JSON data into a date time format (2021-08-31T11:20:42.264+08:00). Sample data below:

{'Id': 'jr_e10ba9a2ab867b3abb3b1f8955cfd1815e1ce00cc981230702dfad45fb49a4b9', 
'Attempt': 0, 
'JobName': 'my_job_name', 
'StartedOn': datetime.datetime(2021, 8, 31, 3, 17, 34, 49000, tzinfo=tzlocal()), 
'LastModifiedOn': datetime.datetime(2021, 8, 31, 3, 19, 34, 855000, tzinfo=tzlocal()), 
'CompletedOn': datetime.datetime(2021, 8, 31, 3, 19, 34, 855000, tzinfo=tzlocal()), 
'JobRunState': 'FAILED'}

Upvotes: 0

Views: 638

Answers (2)

Tzane
Tzane

Reputation: 3472

If you are writing your dictionary to a .json file, you can make your own serializer:

import json

...

def default_serialize(val):
    if isinstance(val, datetime.datetime):
        ret = val.isoformat()
    else:
        ret = str(val)
    return ret

with open("my_data.json", "w") as fp:
    json.dump(dct, fp, indent=4, default=default_serialize)
    # Add empty line at EOF
    fp.write("\n")

Upvotes: 2

Shom77
Shom77

Reputation: 96

datetime luckily has a .isoformat function which will convert a datetime.datetime object to an isoformat, which is close to the one you want above.

You could just iterate through each key/value, and rewrite each key like:

my_json = {'Id': 'jr_e10ba9a2ab867b3abb3b1f8955cfd1815e1ce00cc981230702dfad45fb49a4b9', 
'Attempt': 0, 
'JobName': 'my_job_name', 
'StartedOn': datetime.datetime(2021, 8, 31, 3, 17, 34, 49000, tzinfo=tzlocal()), 
'LastModifiedOn': datetime.datetime(2021, 8, 31, 3, 19, 34, 855000, tzinfo=tzlocal()), 
'CompletedOn': datetime.datetime(2021, 8, 31, 3, 19, 34, 855000, tzinfo=tzlocal()), 
'JobRunState': 'FAILED'}
for key, value in my_json.items():
   if isinstance(value, datetime.datetime):
       my_json[key] = value.isoformat()

This iterates through the key and value of the json, checks if it is a datetime object, then converts it to the specified isoformat.

Please keep in mind that you need to load the JSON if you're loading it from an external file to do this, as JSON parsing in Python will lead to a dictionary, which is what I'm assuming you have here based off of what you gave above.

Upvotes: 1

Related Questions