Issue
I have a pipe separated file with one field containing some information in JSON format:
1|2|{"StartTime":1572300507000,"EndTime":1547506800474,"DeleteTime":1572217199000}|4
In order to retrieve the JSON values I'm using json.loads.
Bellow is a part of my code:
import sys,json,time
with open(sys.argv[1], 'r') as file:
for line in file:
fields = line.split('|')
print time.strftime('"%Y%m%d%H%M%S"', time.localtime(json.loads(fields[2])['StartTime'])
Which doesn't work as expected, since the epoch time has also ms. The simpliest solution would be to devide the epoch with 1000 and do something like this:
time.strftime('"%Y%m%d%H%M%S"', time.localtime(json.loads(fields[2])['StartTime']/1000)
Which of course doesn't work since I'm getting the following error:
TypeError: unsupported operand type(s) for /: 'time.struct_time' and 'int'
Which is the proper way to do this? I'm trying to find also the most efficient way since the file has million of rows.
Solution
You should divide the number, your error is based on mismatched parentheses:
d = '''{"StartTime":1572300507000,"EndTime":1547506800474,"DeleteTime":1572217199000}'''
time.strftime('"%Y%m%d%H%M%S"', time.localtime(json.loads(d)['StartTime']/1000))
Output:
'"20191028230827"'
Answered By - Maurice Meyer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.