I have to read a JSON file and It has the date fields formated like this below
"MyDate": "/Date(1603284014088)/",
I found some examples to parse it in other languages (JavaScript, Kotlin) but nothing in Python.
I could find on this SCOTT HANSELMAN's post here that they are milliseconds since the beginning of the Unix Epoch sometimes with a TimeZone. So I could write a simple function to decode it.
import re
from datetime import datetime, timedelta
def decode_date (encoded_date):
mask = "\/Date\(([0-9]*)\)"
offset = datetime(1970, 1, 1)
my_matchs = re.match(mask, encoded_date).groups()
if len(my_matchs) == 1:
return datetime(1970, 1, 1) + timedelta(milliseconds=int(my_matchs[0]))
else:
return None
encoded = "/Date(1603284014088)/"
print (decode_date(encoded))
This function can't parse dates with timezone because I'm lazy :), My question is - is there some lib that can parse it out of the box in Python?
datetime.fromtimestampto convert the Unix timestamp value directly, there's no need to do it yourself/Date(...)wrapper around it.