【问题标题】:Datetime comparison in Python using JSON dataPython中使用JSON数据的日期时间比较
【发布时间】: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 &lt;module&gt; while time &gt; t1 and time &lt; t2: TypeError: '&gt;' 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 天或更长时间,则会失败。如何解决这个问题?

标签: python json datetime


【解决方案1】:

由于time 变量是一个字符串对象,由于类型不兼容,您无法将其与datetimet1t2)对象进行比较。我认为您可以通过使用函数datetime.datetime.strptimedatetime.datetime.fromisoformat(如@MrFuppes 建议)将time 字符串转换为datetime.datetime 来修复错误。我注意到您已将其注释掉,但我认为您应该取消注释并将其更改为

timestamp = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ")

time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")

time = datetime.datetime.fromisoformat(time)
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')
        time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
        while time > t1 and time < t2:
            print(time)

运行脚本时,会导致while 无限循环,因为我认为这是您正在进行的工作,所以我没有删除它。此外,另一种替代方法是将t1t2 datetime 对象转换为字符串格式%Y-%m-%d %H:%M:%S,以便能够与time 变量进行比较

【讨论】:

  • OPs json中的格式是好的ISO8601,可以使用datetime.fromisoformat更方便
  • 感谢@MrFuppes 的建议,我已经更新了我的答案
  • 感谢它的工作。现在我对代码进行了一些即兴创作,以获得'production_A'和'production_B'的总计数,如下所示` if item.get['production_A'] == True: countA += 1 if item.get['production_B'] == True: countB += 1 print(countA,countB) `它显示错误,因为对象不是object is not subscriptable。我对此很陌生,只能学习。
  • @GaiusGD'cruz 我认为您应该使用item.get(&lt;key&gt;)item[&lt;key&gt;] 以便在字典中获取键&lt;key&gt; 的值。我认为您正在使用item.get[&lt;key&gt;] 的组合。在这种情况下,您应该使用item['production_B']item['production_A']item.get('production_B')item.get('production_A') 来获取字典值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2019-05-12
  • 1970-01-01
  • 2012-01-20
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多