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 :
'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)]