question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How To Retrieve Weather Forecast From OpenWeatherMap For A Given Local Date and Time expressed using Local Time Zone?

See original GitHub issue

OpenWeatherMap API provides a free 5 day weather forecast service with forecast reports at 3 hour intervals per day for a given city.

daily_forecast_data = [UTC date:12:00, UTC date:03:00, UTC date:06:00, UTC date:09:00, UTC date:12:00, UTC date:15:00, UTC date:18:00, UTC date:21:00]

If the requester is in Sydney the UTC time offset is +10:00 hrs.

So assuming the following 5 day forecast time window:

start = 2021-09-03T12:00:00:00:00
end = 2021-09-08T12:00:00:00:00

If I am providing an API endpoint weather server that accepts a city and ISO8601 date string for that city’s local timezone, how do I retrieve the correct weather forecast from OpenWeatherMap for that date and time for that city?

API Sydney Example GET /weather/sydney/?when=2021-09-06T15:00+10:00

This represents querying a forecast for 2021-09-06 3pm in Sydney.

The OpenWeatherMap 5 day forecast for a city gives a response with 3hour reference timestamps reported in UTC for those 5 days.

Would I have to filter the openweathermap resultset for 2021-09-06 and then convert each 3 hour slot’s, reference timestamp to local time to find the closest match to T15:00+10:00?

I have tried using pyorm Python library to facilitate making the request to openweathermap.org:

    owm = OWM("<API KEY>")
    mgr = owm.weather_manager()
    three_h_forecaster = mgr.forecast_at_place("Sydney,AUS", "3h")
    day_iso = "2021-09-06T15:00+10:00:00"

    weather = three_h_forecaster.get_weather_at(day_iso)
    print(f"WEATHER FOR Sydney 3H starts := {three_h_forecaster.when_starts('iso')}")
    print(f"WEATHER FOR Sydney 3H ends := {three_h_forecaster.when_ends('iso')}")
    print(f"Weather for {day_iso} is :: \n{json.dumps(weather.to_dict(), indent=4)}")
    print(f"Weather reference time is: {weather.reference_time('iso')}")
WEATHER FOR Sydney 3H starts := 2021-09-03 15:00:00+00:00
WEATHER FOR Sydney 3H ends := 2021-09-08 12:00:00+00:00
Weather for 2021-09-06T15:00+10:00:00 is :: 
{
    "reference_time": 1630908000,
    "sunset_time": null,
    "sunrise_time": null,
    "clouds": 32,
    "rain": {},
    "snow": {},
    "wind": {
        "speed": 10.42,
        "deg": 193,
        "gust": 14.76
    },
    "humidity": 53,
    "pressure": {
        "press": 1027,
        "sea_level": 1027
    },
    "temperature": {
        "temp": 287.64,
        "temp_kf": 0,
        "temp_max": 287.64,
        "temp_min": 287.64,
        "feels_like": 286.53
    },
    "status": "Clouds",
    "detailed_status": "scattered clouds",
    "weather_code": 802,
    "weather_icon_name": "03d",
    "visibility_distance": 10000,
    "dewpoint": null,
    "humidex": null,
    "heat_index": null,
    "utc_offset": null,
    "uvi": null,
    "precipitation_probability": 0.02
}
Weather reference time is: 2021-09-06 06:00:00+00:00

Am I using this correct? I notice that the reference time reported is 2021-09-06 06:00:00+00:00

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
csparpacommented, Sep 4, 2021

Hi @dcs3spp I would advice to use the OneCall features so that you get fresh data and no backwards-compatibility issues in the long run . And bonus feature: you get forecasted weather with HOURLY granularity (you’re aiming for 3 hours now)

Apart from that, I guess the correct process is:

  1. you accept local time as a parameter (eg. Sidney timezone) to your endpoint
  2. you turn that into UTC and extract the related UNIX epoch
  3. you can pass that UNIX epoch to the utility function: pyowm.utils.weather.find_closest_weather

This is a working example that retrieves forecasted weather on Sidney at 15 hours after you run the code:

from pyowm.owm import OWM
from pyowm.utils.weather import find_closest_weather
from datetime import datetime, timedelta

owm = OWM('YOUR_API_KEY')

gcm = owm.geocoding_manager()
mgr = owm.weather_manager()

# This should be the epoch resulting from turning your endpoint's parameter to UTC...
target_time = int((datetime.utcnow() + timedelta(hours=15)).timestamp())  # UTC epoch for: now + 15 hours

# geocode Sidney
sidney = gcm.geocode('Sidney', 'AU')[0]

# call the API
response = mgr.one_call(lat=sidney.lat, lon=sidney.lon)  # OneCall object containing current and forecast weather on Sidney

# retrieve the forecasted weather that is closest to your target epoch
weathers = response.forecast_hourly
closest_weather = find_closest_weather(weathers, target_time)  # this is what you're looking for!

Is this of any help ?

0reactions
csparpacommented, Sep 11, 2021

Normally you don’t need to specify any timezone when you invoke the OneCall API for a city

As far as I konw, OWM does not provide any timezone detail when looking up for city IDs or geocoding

Nevertheless, Python libraries do exist for this purpose (eg: geopy)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Frequently Asked Questions - OpenWeatherMap
What are the minimum/maximum temperature fields in the Current Weather API and Forecast Weather API? · Which time format and timezone are used?...
Read more >
Find current weather of any city using ... - GeeksforGeeks
Then we will use the select() function to retrieve the particular information like time, info, location, store them in some variable, and, store ......
Read more >
How to obtain Open Weather API date/time from city being ...
Basically followed these steps: Obtain current local time; Find local time offset; Obtain current UTC time; Obtain destination city's offset in ...
Read more >
Date and times in the weather API - Visual Crossing
All dates and times are returned according to the local time of the weather information.
Read more >
Creating a Weather app in Node.js using the ... - Section.io
In this tutorial, the reader will learn how to build a beautiful weather app using OpenWeatherMap API and Node.js.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found