这是我当前的代码:
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"}}}
]
}
Time_1、2和3分别包含火车发车的不同时间。我想检查time_1是否已经过去了,而time_2现在是相关时间。我认为,使用datetime.now获取当前时间,然后使用If / elif检查time_1是否早于datetime.now将会是一个可行的选择。我是编码的新手,所以我不确定这是否是一个好的方法。这项工作是否有效,还有更好的方法吗?
PS:我打算做一个显示器,显示下一趟火车离开的时间。因此,必须一遍又一遍地检查时间是否仍然有意义。
答案 0 :(得分:1)
我不太了解您的问题。我认为您正在尝试比较两次。
首先让我们看一下time_1
的内容:
{'departure': '2018-08-04T15:24:00+0200'}
因此,添加departure
键以访问时间。要将日期和时间字符串解析为python可以理解的时间,我们使用datetime.strptime()
方法。有关datatime.strptime()
经过时间比较的代码的修改版本:
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)
答案 1 :(得分: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有点难看,如果要在其他站点上进行检查,则不方便。最好让requests
通过参数字典为您构建查询URL。并且我们还应该检查请求是否成功,可以使用raise_for_status
方法来完成。
只需用以下内容替换脚本的顶部:
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()
如果您以前从未使用过enumerate
,一开始可能会有些困惑。这是一个简短的演示,演示了三种不同的方式来遍历项目列表并打印每个项目及其索引号。
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