Skip to content Skip to sidebar Skip to footer

Python: How To Change All Instances Of "timestamp" In .JSON File To A Date-time Object

I have a LocationHistory.json file that has location data stored. The data looks like this: { 'data' : { 'items' : [ { 'kind' : 'latitude#location', 'timestampMs' : '

Solution 1:

To get POSIX timestamps from a json file and convert them into naive datetime objects that represent UTC time:

#!/usr/bin/env python
import io
import json
from datetime import datetime, timedelta

with io.open('LocationHistory.json', encoding='utf-8') as file:
    data = json.load(file)
for item in data['data']['items']:
    timestamp_millis = int(item['timestampMs'])
    utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=timestamp_millis)
    print(utc_time.isoformat() + 'Z')

Output

2013-07-26T20:34:56.803000Z
2013-07-26T20:31:51.762000Z

Notice: milliseconds are preserved.


Solution 2:

To extract the data from the location dictionary you can use the get method and then divide the integer by 1000 to get the timestamp without milliseconds:

for location in locations:
    print(datetime.datetime.fromtimestamp(
        int(location.get("timestampMs"))/1000
    ).strftime("%Y-%m-%dT%H:%M:%SZ"))

Post a Comment for "Python: How To Change All Instances Of "timestamp" In .JSON File To A Date-time Object"