This is my code:
import urllib.request
import urllib.parse
x = urllib.request.urlopen('http://transport.opendata.ch/v1/connections?
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure')
data = x.read()`enter code here`
saveFile = open('Ergebnis4.txt', 'w')
saveFile.write(str(data))
saveFile.close()here
When I run it, I get this:
{"connections":[{"from":{"prognosis":{"departure":"2018-06-
07T11:52:00+0200"}}},{"from":{"prognosis":{"departure":"2018-06-
07T12:22:00+0200"}}},{"from":{"prognosis":{"departure":"2018-06-
07T12:53:00+0200"}}},{"from":{"prognosis":{"departure":null}}}]}
However, I only need the Datetime values without the text. How could I achieve that?
You can extract datetimes from the response with regex.
# ...
data = x.read()
dates = re.findall('\d{4}[^+]*\+\d{4}', str(data))
dates = '\n'.join(dates)
saveFile = open('Ergebnis4.txt', 'w')
saveFile.write(dates)
saveFile.close()
You are having a JSON response. You can use the JSON module.
Ex:
import json
with open('Ergebnis4.txt', 'w') as outfile:
for i in json.loads(data)["connections"]:
saveFile.write(i['from']['prognosis']['departure'])
This is how you can get that:
import requests
res = requests.get("http://transport.opendata.ch/v1/connections?from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
for item in res.json()['connections']:
print(item['from']['prognosis']['departure'])
Output:
2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
None
Or using urllib module:
from urllib.request import urlopen
import json
res = urlopen("http://transport.opendata.ch/v1/connections?from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
for item in json.load(res)['connections']:
print(item['from']['prognosis']['departure'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.