Reputation:
This is my current code:
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']
The JSON data looks like this:
{
"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 and 3 all contain different times where the train departs. I want to check if time_1 is already in the past, and time_2 now is the relevant time. In my opinion, using datetime.now to get the current time and then using If / elif to check if time_1 is sooner than datetime.now would be a viable option. I am new to coding, so I am unsure if this is a good way of doing it. Would this work and are there any better ways?
PS: I am planning to make a display that displays the time the next train leaves. Therefore, it would have to check if the time is still relevant over and over again.
Upvotes: 0
Views: 235
Reputation: 55479
The following code extracts all the departure time strings from the JSON data, and converts the valid time strings to datetime objects. It then prints the current time, and then a list of the departure times that are still in the future.
Sometimes the converted JSON has None
for a departure time, so we need to deal with that. And we need to get the current time as a timezone-aware object. We could just use the UTC timezone, but it's more convenient to use the local timezone from the JSON data.
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))
output
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
That query URL is a bit ugly, and not convenient if you want to check on other stations. It's better to let requests
build the query URL for you from a dictionary of parameters. And we should also check that the request was successful, which we can do with the raise_for_status
method.
Just replace the top section of the script with this:
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()
If you've never used enumerate
before, it can be a little confusing at first. Here's a brief demo of three different ways to loop over a list of items and print each item and its index number.
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
Upvotes: 1
Reputation: 1058
I didn't understand your question properly. I think you are trying to compare two time.
First let's see the contents of time_1
:
{'departure': '2018-08-04T15:24:00+0200'}
So add departure
key to access time. To parse the date and time string to python understandable time we use datetime.strptime()
method. See this link for further description on datatime.strptime()
The modified version of your code that does time comparision:
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)
Upvotes: 0