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'
CodePudding user response:
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)]
CodePudding user response:
One of the approaches to solve your problem is to use a list comprehension such as:
from datetime import datetime
import re
# Your code to extract data from JSON file and assign them to `birthdate_json` variable
[datetime.fromtimestamp(float((re.search("Date\((. )\)",x).group(1)))/1000).strftime("%Y-%m-%d") for x in birthdate_json]
which regarding the example of birthdate_json[:5]
would result in:
['2002-02-09', '2002-03-20', '2002-01-08', '2002-03-27', '2002-04-29']
CodePudding user response:
These times are in epoch milliseconds. You can convert them to a datetime
object:
import datetime
x = datetime.datetime.fromtimestamp(int("1013230800000")/1000)
print(x.strftime("%F"))
>>> 2002-02-09