0

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'}
1
  • That's not JSON Commented Aug 31, 2021 at 3:47

2 Answers 2

2

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")

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.