Python 使用datetime评估给定时间是否已在过去

Python 使用datetime评估给定时间是否已在过去,python,datetime,Python,Datetime,这是我当前的代码: import requests import json res = requests.get("http://transport.opendata.ch/v1/connections? from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure") parsed_json = res.json() time_1 = parsed_json['connectio

这是我当前的代码:

import requests
import json

res = requests.get("http://transport.opendata.ch/v1/connections? 
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")

parsed_json = res.json()

time_1 = parsed_json['connections'][0]['from']['prognosis']
time_2 = parsed_json['connections'][1]['from']['prognosis']
time_3 = parsed_json['connections'][2]['from']['prognosis']
JSON数据如下所示:

{
    "connections": [
        {"from": {"prognosis": {"departure": "2018-08-04T14:21:00+0200"}}},
        {"from": {"prognosis": {"departure": "2018-08-04T14:53:00+0200"}}},
        {"from": {"prognosis": {"departure": "2018-08-04T15:22:00+0200"}}},
        {"from": {"prognosis": {"departure": "2018-08-04T15:53:00+0200"}}}
    ]
}
时间_1、2和3都包含列车出发的不同时间。我想检查时间1是否已经过去,而时间2现在是相关时间。在我看来,使用datetime.now获取当前时间,然后使用If/elif检查time_1是否早于datetime.now将是一个可行的选择。我对编码还不熟悉,所以我不确定这是否是一种很好的方法。这行得通吗?还有更好的办法吗


PS:我计划做一个显示屏,显示下一班火车离开的时间。因此,它必须反复检查时间是否仍然相关。

我没有正确理解你的问题。我想你是想比较两次

首先让我们看一下时间1的内容:

{‘出发’:'2018-08-04T15:24:00+0200'}

因此,在访问时间中添加
离开
键。要将日期和时间字符串解析为python可理解的时间,我们使用
datetime.strtime()
方法。有关
datatime.strtime()

执行时间比较的代码的修改版本:

import requests
import json
from datetime import datetime

res = requests.get("http://transport.opendata.ch/v1/connections? from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")

parsed_json = res.json()

time_1 = parsed_json['connections'][0]['from']['prognosis']['departure']
time_2 = parsed_json['connections'][1]['from']['prognosis']['departure']
time_3 = parsed_json['connections'][2]['from']['prognosis']['departure']

mod_time_1 = datetime.strptime(time_1,'%Y-%m-%dT%H:%M:%S%z')
mod_time_2 = datetime.strptime(time_2,'%Y-%m-%dT%H:%M:%S%z')

# you need to provide datetime.now() your timezone.
timezone = mod_time_1.tzinfo
time_now = datetime.now(timezone)
print(time_now > mod_time_1)

下面的代码从JSON数据中提取所有离开时间字符串,并将有效的时间字符串转换为datetime对象。然后,它打印当前时间,然后是未来的出发时间列表

有时转换后的JSON在一段时间内没有None,所以我们需要处理这个问题。我们需要将当前时间作为时区感知对象。我们可以只使用UTC时区,但从JSON数据使用本地时区更方便

import json
from datetime import datetime
import requests

url = "http://transport.opendata.ch/v1/connections? from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure"
res = requests.get(url)
parsed_json = res.json()

# Extract all the departure time strings from the JSON data
time_strings = [d["from"]["prognosis"]["departure"]
    for d in parsed_json["connections"]]
#print(time_strings)

# The format string to parse ISO 8601 date + time strings 
iso_format = "%Y-%m-%dT%H:%M:%S%z"

# Convert the valid time strings to datetime objects 
times = [datetime.strptime(ts, iso_format) 
    for ts in time_strings if ts is not None]

# Grab the timezone info from the first time
tz = times[0].tzinfo
# The current time, using the same timezone
nowtime = datetime.now(tz)
# Get rid of the microseconds
nowtime = nowtime.replace(microsecond=0)
print('Now', nowtime)

# Print the times that are still in the future
for i, t in enumerate(times):
    if t > nowtime:
        diff = t - nowtime
        print('{}.  {} departing in {}'.format(i, t, diff))
输出

Now 2018-08-04 17:17:25+02:00
1.  2018-08-04 17:22:00+02:00 departing in 0:04:35
2.  2018-08-04 17:53:00+02:00 departing in 0:35:35
3.  2018-08-04 18:22:00+02:00 departing in 1:04:35

该查询URL有点难看,如果您想查看其他站点,则不方便。最好让
请求
从参数字典中为您构建查询URL。我们还应该检查请求是否成功,这可以通过该方法实现

只需将脚本的顶部替换为以下内容:

import json
from datetime import datetime
import requests

endpoint = "http://transport.opendata.ch/v1/connections"

params = {
    "from": "Baldegg_kloster",
    "to": "Luzern",
    "fields[]": "connections/from/prognosis/departure",
}

res = requests.get(endpoint, params=params)
res.raise_for_status()
parsed_json = res.json()

如果您以前从未使用过,一开始可能会有点困惑。下面是三种不同方法的简要演示,它们可以循环遍历项目列表并打印每个项目及其索引号

things = ['zero', 'one', 'two', 'three']
for i, word in enumerate(things):
    print(i, word)

for i in range(len(things)):
    word = things[i]
    print(i, word)

i = 0
while i < len(things):
    word = things[i]
    print(i, word)
    i = i + 1
things=['0','1','2','3']
对于我,列举(事物)中的单词:
打印(i,word)
对于范围内的i(len(things)):
单词=事物
打印(i,word)
i=0
当我(事情)发生时:
单词=事物
打印(i,word)
i=i+1

时间的格式如何?你能添加一些输入示例吗?谢谢你简洁明了的回答,它真的帮了我很大的忙!然而,我仍然有一个问题:在for循环中,I和t代表什么?我把I改成a,t改成b,它仍然有效。现在我很困惑,这个节目是如何知道我和t代表什么的。@DominikSidler我很高兴我的回答帮助了你。请考虑一下。在
for
循环中,我们使用函数在
时间
列表上循环。在循环的每次迭代中,
t
被设置为列表中的下一个
datetime
,而
i
是循环索引:一个从0开始的计数器。@DominikSidler我们可以使用我们喜欢的任何名称,我只是使用
i
作为索引,因为这是一种常见的做法,我使用
t
代表
时间。我想我应该用一个更有意义的名字,比如《离别时间》,但我很懒您可能会发现这篇文章很有帮助:,它是由经验丰富的Ned Batchelder撰写的。谢谢,但我仍然感到困惑:程序如何知道
I
代表索引而
t
代表时间?因为我认为必须在定义
x=25
@DominikSidler时定义它们,所以程序并不真正“知道”I
代表索引。在通过
for
循环的每一轮中,
enumerate(times)
生成一个
(index,value)
对,(其中
value
times
列表中的下一项),而
for i,t in…
语法表示将该对分配给
i
t