【发布时间】:2021-04-07 12:42:59
【问题描述】:
我正在编写一个脚本来加载 json 文件并提取特定时间戳内的值。这是我的代码。
import json,datetime
t1 = "2021-01-28T01:30:00Z"
t2 = "2021-01-29T10:10:00Z"
t1 = datetime.datetime.strptime(t1, "%Y-%m-%dT%H:%M:%SZ")
t2 = datetime.datetime.strptime(t2, "%Y-%m-%dT%H:%M:%SZ")
with open('sample.json') as f:
data = json.load(f)
for item in data:
time = item.get('time')
#timestamp = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ")
while time > t1 and time < t2:
print(time)
我得到的错误是Traceback (most recent call last): File "C:\Users\titto\Desktop\test.py", line 12, in <module> while time > t1 and time < t2: TypeError: '>' not supported between instances of 'str' and 'datetime.datetime'
JSON 格式就是这个。具有以下键的值列表。我想检查给定的时间限制并获取每个生产的真实值的总数。
{
"time": "2021-01-29 09:30:00",
"production_A": false,
"production_B": false
},
{
"time": "2021-01-29 09:50:00",
"production_A": true,
"production_B": false
},
{
"time": "2021-01-29 10:10:00",
"production_A": true,
"production_B": true
},
【问题讨论】:
-
使用
time = datetime.datetime.fromisoformat(item.get('time'))使变量time也成为日期时间对象。 -
@MrFuppes 如果我想在特定的时间段内检查每个生产的真实值,比如每天上午 9 点到下午 2 点。我将如何做到这一点。给定的格式是 24 小时制。
-
据我了解,您的
for循环会迭代 json 中的所有记录。现在我想你会想要一个if语句而不是while循环。如果时间戳在您的限制范围内,请检查生产密钥并在 True 时继续。在电话上,无法输入实际答案;-) -
@MrFuppes 是的,我将其更正为 if。例如,如果我想检查从 start = "2021-01-28T06:00:00Z" end = "2021-01-29T18:00:00Z" 开始的数据并且我想检查一批说 6 AM - 2 PM这两天。我该如何实现这一点。我尝试的版本是我将上午 6 点转换为
datetime.datetime.strptime(t1, "%Y-%m-%dT%H:%M:%SZ")这种格式,下午 2 点也是如此。但这仅适用于一天,因为我还必须使用格式给出日期。如果输入范围超过 2 天或更长时间,则会失败。如何解决这个问题?