Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert JSON date list to python date format

I’ve got this list of birthdate that is in JSON format, that I want to convert to Python format. What would be the easiest way to convert to python date format?

print(birthdate_json[:5])

gives me the following results :

['/Date(1013230800000)/', '/Date(1016600400000)/', '/Date(1010466000000)/', '/Date(1017205200000)/', '/Date(1020052800000)/']

While I would the desired input to be :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'2002-02-09', '2002-03-20', '2002-01-08', '2002-03-27', '2002-04-29'

>Solution :

You can use datetime.fromtimestamp() in datetime module to convert epochtime to datetime, as follows:

from datetime import datetime

birthdate_json = [
    '/Date(1013230800000)/',
    '/Date(1016600400000)/',
    '/Date(1010466000000)/',
    '/Date(1017205200000)/',
    '/Date(1020052800000)/'
]
birthdate = []
for i in range(len(birthdate_json)):
    epoch_time = int(birthdate_json[i][6:-2])/1000
    datetime_type_value = datetime.fromtimestamp(epoch_time)
    # uncomment next line If you want str value of datetime such as ["2022-02-23", "2022-02-24" ...]
    # datetime_type_value = datetime_type_value.strftime("%F")
    birthdate.append(datetime_type_value)

print(birthdate)

# datetime type values will be printed:
# [datetime.datetime(2002, 2, 9, 14, 0), datetime.datetime(2002, 3, 20, 14, 0), datetime.datetime(2002, 1, 8, 14, 0), datetime.datetime(2002, 3, 27, 14, 0), datetime.datetime(2002, 4, 29, 13, 0)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading