用Python更改Json文件中的内部元组

2024-05-03 14:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Json,看起来像:

[
  {
    "id": "a199ffc8-86d3-4ed1-a5e1-87ed11b89e21",
    "times": [
      {
        "start": 1543683600000,
        "end": 1543791600000
      },
      {
        "start": 1543827600000,
        "end": 1543899600000
      }
    ],
    "priority": "P1"
  },
  {
    "id": "e9d5ad69-806b-4c77-8be4-5be6d41db1c9",
    "times": [
      {
        "start": 1543647600000,
        "end": 1543683600000
      },
      {
        "start": 1543719600000,
        "end": 1543755600000
      }
    ],
    "priority": "P1"
  }]

我试图改变“开始”和“结束”的时间戳,但我不能完全弄清楚怎么做。你写了这样的东西:

from datetime import timedelta


with open('events.json') as json_file:
    data = json.load(json_file, )


day_start = 28
for tuple in data:
    tuple['start'] =  (calendar.timegm(time.gmtime()) - int(timedelta(days = day_start).total_seconds()))*1000
    tuple['end'] =  (calendar.timegm(time.gmtime()) - int(timedelta(days = day_start-1).total_seconds()))*1000
    day_start -= 2


with open('dataEvents.json', 'w') as outfile:
    json.dump(data, outfile)

为了进入正确的领域,有什么需要改变的吗?你知道吗


Tags: idjsondataaswithopenstartfile
1条回答
网友
1楼 · 发布于 2024-05-03 14:02:28

如果您想将每一个startend数据的时间倒转若干天,您需要遍历dict元素的times键,而不仅仅是遍历dict的所有元素

import time

print('before:')
print(*data[0]['times'], sep='\n')
print(*data[1]['times'], sep='\n')

day_start = 28
for i in data:
    for pair in i['times']:
        pair['start'] = int((time.time() - day_start*60*60*24) * 1000)
        pair['end'] = int((time.time() - day_start-1*60*60*24) * 1000)
        day_start -= 2

print('\nafter:')
print(*data[0]['times'], sep='\n')
print(*data[1]['times'], sep='\n')

输出

before:
{'end': 1543791600000, 'start': 1543683600000}
{'end': 1543899600000, 'start': 1543827600000}
{'end': 1543683600000, 'start': 1543647600000}
{'end': 1543755600000, 'start': 1543719600000}

after:
{'end': 1547892092406, 'start': 1545559320406}
{'end': 1547892094406, 'start': 1545732120406}
{'end': 1547892096406, 'start': 1545904920406}
{'end': 1547892098406, 'start': 1546077720406}

相关问题 更多 >