Good day to all! I ask for your help, there is a code:

import requests from datetime import datetime, date, time city = input() r = requests.get('http://api.openweathermap.org/data/2.5/forecast?&units=metric&q=%s&appid=295f286d77a869327ed8dfae72a0542d' % (city)) data = r.json() temp = data["list"] for id in temp: tmp = id["main"]["temp"] tmp = str(round(tmp)) dt = id["dt_txt"] print(dt + " - " + tmp + "°C") 

Which by the name of the city gives the weather for 5 days. That only gives it periods of 3 hours. Those. for 24 will give 8 values. 5 days - 40

enter image description here

To set the displayed number of values, I can write temp = data["list"][*number*] in the code. The problem is that the weather is displayed depending on the time, i.e. if I run the script at 18, it will show the weather from 18:00. If I start at 9 am, it will show from 9 am. Proceeding from this, I cannot set in temp = data["list"] [8] as the weather will appear not only for today, but also for tomorrow. And constantly, based on the time, I do not have to enter the required number of output values.

How can I make a check that if until the end of today there are 6 hours left, then in temp = data["list"] to betray the value [2] . If it remains 12 hours - then pass [4] .

I would be very grateful for your reply.

  • one
    You can try a couple of options: (a) set the parameters of the http-request so that only for the time interval of interest to you the values ​​would be returned (if it supports service-weather — read its docks) (b) filter on the client: data = [id for id in temp if start_time <= id['dt'] < end_time] - jfs

2 answers 2

You can do this:

 from datetime import datetime def dt_convert(dt_str, fmt_from='%Y-%m-%d %H:%M:%S', fmt_to='%m/%d %a %H:%M'): return datetime.strptime(dt_str, fmt_from).strftime(fmt_to) today = datetime.now().strftime('%Y-%m-%d') forecast_today = \ ['{} - {}°C'.format(dt_convert(x['dt_txt']), round(x['main']['temp'])) for x in data['list'] if x['dt_txt'].startswith(today) ] 

Result:

 ['01/25 Wed 00:00 - -14°C', '01/25 Wed 03:00 - -14°C', '01/25 Wed 06:00 - -13°C', '01/25 Wed 09:00 - -11°C', '01/25 Wed 12:00 - -8°C', '01/25 Wed 15:00 - -9°C', '01/25 Wed 18:00 - -16°C', '01/25 Wed 21:00 - -15°C'] 

PS If you need to display the date in a "non-native" (different from the system) locale, then you can use PyICU or Pendulum (you may have difficulty installing on Win64)

    What does not like this option. We can easily get the current date, then look at the number of hours. And - wala:

     import datetime time = datetime.datetime.now() number = (24 - time.hour - 1) // 3 print data["list"][number] 
    • TypeError: 'datetime.datetime' object is not subscriptable swears at number = ((24 - time[2] - 1) // 3) - Vladimir V.
    • Corrected. In your post, * number * is int? - hedgehogues