A thin Python Wrapper for the Dark Sky (formerly forecast.io) weather API

Overview

Dark Sky Wrapper

https://travis-ci.org/ZeevG/python-forecast.io.svg?branch=master

This is a wrapper for the Dark Sky (formerly forecast.io) API. It allows you to get the weather for any location, now, in the past, or future.

The Basic Use section covers enough to get you going. I suggest also reading the source if you want to know more about how to use the wrapper or what its doing (it's very simple).

Installation

You should use pip to install python-forecastio.

  • To install pip install python-forecastio
  • To remove pip uninstall python-forecastio

Simple!

Requirements

Basic Use

Although you don't need to know anything about the Dark Sky API to use this module, their docs are available at https://darksky.net/dev/.

To use the wrapper:

import forecastio

api_key = "YOUR API KEY"
lat = -31.967819
lng = 115.87718

forecast = forecastio.load_forecast(api_key, lat, lng)
...

The load_forecast() method has a few optional parameters. Providing your API key, a latitude and longitude are the only required parameters.

Use the forecast.DataBlockType() eg. currently(), daily(), hourly(), minutely() methods to load the data you are after.

These methods return a DataBlock. Except currently() which returns a DataPoint.

byHour = forecast.hourly()
print byHour.summary
print byHour.icon

The .data attributes for each DataBlock is a list of DataPoint objects. This is where all the good data is :)

for hourlyData in byHour.data:
        print hourlyData.temperature

Advanced

function forecastio.load_forecast(key, latitude, longitude)

This makes an API request and returns a Forecast object (see below).

Parameters:
  • key - Your API key from https://darksky.net/dev/.
  • latitude - The latitude of the location for the forecast
  • longitude - The longitude of the location for the forecast
  • time - (optional) A datetime object for the forecast either in the past or future - see How Timezones Work below for the details on how timezones are handled in this library.
  • lang - (optional) A string of the desired language. See https://darksky.net/dev/docs/time-machine for supported languages.
  • units - (optional) A string of the preferred units of measurement, "auto" is the default. "us","ca","uk","si" are also available. See the API Docs (https://darksky.net/dev/docs/forecast) for exactly what each unit means.
  • lazy - (optional) Defaults to false. If true the function will request the json data as it is needed. Results in more requests, but maybe a faster response time.
  • callback - (optional) Pass a function to be used as a callback. If used, load_forecast() will use an asynchronous HTTP call and will not return the forecast object directly, instead it will be passed to the callback function. Make sure it can accept it.

function forecastio.manual(url)

This function allows manual creation of the URL for the Dark Sky API request. This method won't be required often but can be used to take advantage of new or beta features of the API which this wrapper does not support yet. Returns a Forecast object (see below).

Parameters:
  • url - The URL which the wrapper will attempt build a forecast from.
  • callback - (optional) Pass a function to be used as a callback. If used, an asynchronous HTTP call will be used and forecastio.manual will not return the forecast object directly, instead it will be passed to the callback function. Make sure it can accept it.

class forecastio.models.Forecast

The Forecast object, it contains both weather data and the HTTP response from Dark Sky

Attributes
  • response
  • http_headers
    • A dictionary of response headers. 'X-Forecast-API-Calls' might be of interest, it contains the number of API calls made by the given API key for today.
  • json
    • A dictionary containing the json data returned from the API call.
Methods
  • currently()
    • Returns a ForecastioDataPoint object
  • minutely()
    • Returns a ForecastioDataBlock object
  • hourly()
    • Returns a ForecastioDataBlock object
  • daily()
    • Returns a ForecastioDataBlock object
  • update()
    • Refreshes the forecast data by making a new request.

class forecastio.models.ForecastioDataBlock

Contains data about a forecast over time.

Attributes (descriptions taken from the darksky.net website)
  • summary
    • A human-readable text summary of this data block.
  • icon
    • A machine-readable text summary of this data block.
  • data
    • An array of ForecastioDataPoint objects (see below), ordered by time, which together describe the weather conditions at the requested location over time.

class forecastio.models.ForecastioDataPoint

Contains data about a forecast at a particular time.

Data points have many attributes, but not all of them are always available. Some commonly used ones are:

Attributes (descriptions taken from the darksky.net website)
  • summary - A human-readable text summary of this data block.
  • icon - A machine-readable text summary of this data block.
  • time - The time at which this data point occurs.
  • temperature - (not defined on daily data points): A numerical value representing the temperature at the given time.
  • precipProbability - A numerical value between 0 and 1 (inclusive) representing the probability of precipitation occurring at the given time.

For a full list of ForecastioDataPoint attributes and attribute descriptions, take a look at the Dark Sky data point documentation (https://darksky.net/dev/docs/response#data-point)


How Timezones Work

Requests with a naive datetime (no time zone specified) will correspond to the supplied time in the requesting location. If a timezone aware datetime object is supplied, the supplied time will be in the associated timezone.

Returned times eg the time parameter on the currently DataPoint are always in UTC time even if making a request with a timezone. If you want to manually convert to the locations local time, you can use the offset and timezone attributes of the forecast object.

Typically, would would want to do something like this:

# Amsterdam
lat  = 52.370235
lng  = 4.903549
current_time = datetime(2015, 2, 27, 6, 0, 0)
forecast = forecastio.load_forecast(api_key, lat, lng, time=current_time)

Be caerful, things can get confusing when doing something like the below. Given that I'm looking up the weather in Amsterdam (+2) while I'm in Perth, Australia (+8).

# Amsterdam
lat  = 52.370235
lng  = 4.903549

current_time = datetime.datetime.now()

forecast = forecastio.load_forecast(api_key, lat, lng, time=current_time)

The result is actually a request for the weather in the future in Amsterdam (by 6 hours). In addition, since all returned times are in UTC, it will report a time two hours behind the local time in Amsterdam.

If you're doing lots of queries in the past/future in different locations, the best approach is to consistently use UTC time. Keep in mind datetime.datetime.utcnow() is still a naive datetime. To use proper timezone aware datetime objects you will need to use a library like pytz

Comments
  • Support for naïve datetime objects

    Support for naïve datetime objects

    Ref Issue 21.

    The .load_forecast() method is currently converting the datetime argument to seconds since the epoch in local time, which has the effect of making it an "aware" datetime. That is, it imbues the datetime with statefulness w.r.t. location that it doesn't necessarily have already, if it's passed as a naïve datetime (i.e. "5 o'clock somewhere", not necessarily "5 o'clock in Greenwich.")

    Technically, the issue is that time.mktime() takes an argument in local time (i.e. the locale of my laptop) and converts to seconds since the epoch (docs). In the API though, they expect a naïve datetime, unless timezone is specified. From the API docs:

    For the latter format, if no timezone is present, local time (at the provided latitude and longitude) is assumed. (This string format is a subset of ISO 8601 time. An as example, 2013-05-06T12:00:00-0400.)

    My thought was, that in order to make the wrapper as thin as possible, that it should behave in the same way. Instead of using mktime(), it should use isoformat().

    In [1]: %paste
    import time
    import datetime
    from delorean import Delorean
    
    ## -- End pasted text --
    
    In [2]: d = datetime.datetime(2015, 4, 11, 2, 45)  # initialized without any tzinfo
    
    In [3]: d.isoformat()  # this format has no tzinfo, is naïvely unaware of location
    Out[3]: '2015-04-11T02:45:00'
    
    In [4]: ep = time.mktime(d.timetuple())
    
    In [5]: ep  # this number is only associated with datetime(2015, 4, 11, 2, 45) in the sense of GMT-04:00 (I'm in New York.) So it's no longer naïve to location.
    Out[5]: 1428734700.0
    
    In [6]: dl = Delorean(d, timezone="US/Mountain")  # use delorean to create a timezone-aware datetime.datetime
    
    In [7]: dl.datetime  
    Out[7]: datetime.datetime(2015, 4, 11, 2, 45, tzinfo=<DstTzInfo 'US/Mountain' MDT-1 day, 18:00:00 DST>)
    
    In [8]: dl.datetime.isoformat()  # in this case timezone info would be passed on to the API.
    Out[8]: '2015-04-11T02:45:00-06:00'
    
    opened by hack-c 12
  • Support language

    Support language

    Under the Docs for v2 is an lang= Option. It would be nice to see this implemented as something like this:

    foo = forecastio.load_forecast(key, latitude, longitude, lang="en")
    

    This was added to the API on 29 May 2014: https://developer.forecast.io/docs/v2#options

    Currently this is not working. Are there any quick workarounds?

    enhancement 
    opened by luckydonald 12
  • not downloading on raspberry pi (raspbian)

    not downloading on raspberry pi (raspbian)

    entered the command sudo pip install python-forecastio in to terminal and it come out with this: (yes i do have PIP)


    pi@raspberrypi ~ $ sudo pip install python-forecastio Downloading/unpacking python-forecastio Running setup.py egg_info for package python-forecastio

    Downloading/unpacking requests>=1.6 (from python-forecastio) Running setup.py egg_info for package requests

    Downloading/unpacking responses (from python-forecastio) Running setup.py egg_info for package responses No handlers could be found for logger "main"

    Downloading/unpacking cookies (from responses->python-forecastio) Running setup.py egg_info for package cookies

    Requirement already satisfied (use --upgrade to upgrade): six in /usr/local/lib/python2.7/dist-packages (from responses->python-forecastio) Downloading/unpacking mock (from responses->python-forecastio) Running setup.py egg_info for package mock mock requires setuptools>=17.1. Aborting installation Complete output from command python setup.py egg_info: mock requires setuptools>=17.1. Aborting installation


    Command python setup.py egg_info failed with error code 1 in /home/pi/build/mock Storing complete log in /root/.pip/pip.log

    opened by bman46 11
  • Fix time representation and timezone issues

    Fix time representation and timezone issues

    The way times (and dates) are handled is inconsistent and needs an overhaul.

    Times are represented using a mix Python datetime objects and unix timestamps. This needs to be standardised to Python objects. Also, when using times, it is not clear what time zone the API expects. Is it local time or the time at the forecast location? This all needs to be cleaned up and documented.

    One option (this is the approach that Forecast.io has taken) is to always use UTC time.

    This is probably my prefered approach as it will standardise the representation of time within the wrapper and also between the wrapper and the HTTP API.

    opened by ZeevG 10
  • Added language parameter to support i18n of Dark Sky API

    Added language parameter to support i18n of Dark Sky API

    Added the ability to control the language parameter for Dark Sky. This is needed for my modifications for the Home Assistant Dark Sky Sensor where I want to have german weather forecasts :-) So it would be great if you could release a new version of your library and I'll raise the version of the dependency accordingly in order to finish my Home Assistant pull request.

    Thanks!

    opened by nodomain 9
  • Update API endpoint

    Update API endpoint

    As per today's announcement:

    The API endpoint has changed from https://api.forecast.io/ to https://api.darksky.net/. The previous endpoint will continue to work for the foreseeable future, but please change your software as soon as possible.

    opened by RoyalTS 7
  • Ability to pass a simple address string to get a forecast

    Ability to pass a simple address string to get a forecast

    Hello,

    Thanks for creating this wrapper! I've added the ability for the user to enter a simple string that can be geocoded using Geopy instead of having to pass in an explicit lat and long. Adding this feature of course adds another dependency.

    I've also updated example.py to demonstrate how this would be used, and updated the test suite, however since it doesn't appear to actually call load_forecast, it's not really getting tested.

    opened by dstegelman 5
  • Pip install not working

    Pip install not working

    Hey,

    This is super useful and I love it. Had to install manually as pip install couldn't find a matching package. When I searched for it, it recommended python-forcastio (<--that's not a typo), but said there was no matching version for pypi to install.

    opened by dharamsk 4
  • Forecast __unicode__ attribute error

    Forecast __unicode__ attribute error

    I'm running into an issue, whether I use forecastio with 2.7 or 3.4, where I'm getting the following error:

    AttributeError: "'Forecast' object has no attribute 'unicode'"

    Not sure what I'm doing wrong or if this is a legit bug. Thanks in advance!

    opened by CelestialReaver 4
  • Problems installing on mac, python 3.4.1

    Problems installing on mac, python 3.4.1

    Maybe you can have a look, not sure if it is related to your package, but other modules did install.

    Install packages failed: Error occurred when installing package python-forecastio. 
    
    The following command was executed:
    
    packaging_tool.py install --build-dir /private/var/folders/gj/84mj91y514z79t19xfc8t8sr0000gn/T/pycharm-packaging5452297355347498062.tmp --user python-forecastio
    
    The error output of the command:
    
    Traceback (most recent call last):
      File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 56, in do_install
        import pip
      File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/__init__.py", line 10, in <module>
        from pip.util import get_installed_distributions, get_prog
      File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/util.py", line 18, in <module>
        from pip._vendor.distlib import version
      File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/_vendor/distlib/version.py", line 14, in <module>
        from .compat import string_types
      File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/_vendor/distlib/compat.py", line 66, in <module>
        from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
    ImportError: cannot import name 'HTTPSHandler'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 125, in main
        retcode = do_install(pkgs)
      File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 58, in do_install
        error_no_pip()
      File "/Applications/PyCharm.app/helpers/packaging_tool.py", line 36, in error_no_pip
        tb = sys.exc_traceback
    AttributeError: 'module' object has no attribute 'exc_traceback'
    
    opened by luckydonald 4
  • added an option to view forecastio irradiance data

    added an option to view forecastio irradiance data

    Forecast.io has a beta option to view irradiance data. I'd like be able to use this, so I added the parameter solar to the method: forecastio.api.load_forecast

    The way to view this data would be:

    import forecastio from forecastio.utils import PropertyUnavailable forecast = forecastio.load_forecast('%^&!@#(@&#@()$#',37.8267,-122.423, solar=True) byHour = forecast.hourly() for hourlyData in byHour.data: try: print hourlyData.time, hourlyData.solar except PropertyUnavailable: pass

    This irradiance data is only available during daylight hours, which is why you we need to skip occasionally.

    opened by jetheurer 4
  • Can we no longer get an API key?

    Can we no longer get an API key?

    I am trying to run a basic Python example from your GitHub repo for which I need an API key. Your website says "We are no longer accepting new signups." Does this mean it is no longer possible to obtain an API key?

    opened by Neeha-DataScience 1
  • Can't handle for forecastio.utils.PropertyUnavailable keyError

    Can't handle for forecastio.utils.PropertyUnavailable keyError

    I've got a script built to report daily data forecasts, but sometimes I get the forecastio.utils.PropertyUnavailable error. I understand that this means there is no data for the particular forecast item I'm looking for. What I'm asking is how do I handle for these errors? This error is causing my script not to finish retrieving the forecast because of this error.

    Traceback (most recent call last):
      File "/home/user/.local/lib/python3.6/site-packages/forecastio/models.py", line 103, in __getattr__
        return self.d[name]
    KeyError: 'precipType'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "DarkSky.py", line 100, in <module>
        main()
      File "DarkSky.py", line 97, in main
        getDaily(forecast_data)
      File "DarkSky.py", line 70, in getDaily
        'Precip_Type' : i.precipType,
      File "/home/user/.local/lib/python3.6/site-packages/forecastio/models.py", line 107, in __getattr__
        " or is not available for this forecast".format(name)
    forecastio.utils.PropertyUnavailable: Property 'precipType' is not valid or is not available for this forecast
    

    I'd be fine with being able to say something like: 'Precipitation Type: none or no precipitation type data exists for this forecast'

    The problem is I can't figure out how to handle for this error.

    I've tried

    
    exception KeyError:
        print('No data exists for this forecast variable')
    

    and

    exception forecastio.utils.PropertyUnavailable:
        print('No data exists for this forecast variable')
    

    But neither of these work. I noticed in the traceback that this ultimately results from a KeyError exception, but using this as an Exception raise doesn't work.

    Can anyone help with how to handle for these errors? Thanks

    opened by Cerberus2012 2
  • Flags Object

    Flags Object

    What is the correct way to create a Flag Object so that I can then proceed to gather the following data:

    nearest-station required The distance to the nearest weather station that contributed data to this response. Note, however, that many other stations may have also been used; this value is primarily for debugging purposes. This property's value is in miles (if US units are selected) or kilometers (if SI units are selected). sources required This property contains an array of IDs for each data source utilized in servicing this request. units required Indicates the units which were used for the data in this request.

    I have been successful at creating DataPoint Objects, DataBlock Objects, and Alerts Arrays; but so far I have been unable to create a flag object. I cant find any documentation as to how to properly create one, I have been trying this:

    forecast = forecastio.load_forecast(api_key, lat, lng)
    ws = forecast.flags()
    

    but it yields:

    AttributeError: 'Forecast' object has no attribute 'flags'
    

    I need it to find out from what weather station is being used.

    Thanks!!!

    opened by kqi914 0
  • alerts not updated

    alerts not updated

    when a call to Forecast update() is made, the alerts don't seem to get updated

    in init you have

            self._alerts = []
            for alertJSON in self.json.get('alerts', []):
                self._alerts.append(Alert(alertJSON))
    

    but in update nothing happens to _alerts

    is that on purpose?

    opened by leoscholl 0
  • Is it possible to

    Is it possible to "exclude" data blocks to reduce latency?

    I only need to get forecast.currently(). So, I would like to exclude getting the minutely, hourly, daily, alerts, and flags data (to reduce latency).

    The Dark Sky documentation supports an exclude parameter. Does the python-forecast.io library accept this parameter?

    opened by AFishNamedFish 0
Releases(v1.3.3)
Asynchronous wrapper for wttr.in weather forecast.

aiopywttr Asynchronous wrapper for wttr.in weather forecast. Synchronous version here. Installation pip install aiopywttr Example This example prints

Almaz 4 Dec 24, 2022
Wrapper for wttr.in weather forecast.

pywttr Wrapper for wttr.in weather forecast. Asynchronous version here. Installation pip install pywttr Example This example prints the average temper

Almaz 6 Dec 25, 2022
Design and build a wrapper for the Open Weather API current weather data service

Design and build a wrapper for the Open Weather API current weather data service that returns a city's temperature, with caching, also allowing for the temperature of the latest queried cities that are still validly cached to be retrieved.

Duan Rafael Ribeiro 1 Jun 27, 2022
Home Assistant for Opendata CWB. Get the weather forecast of the city in Taiwan.

Home assistant support for Opendata CWB. The readme in Traditional Chinese. This integration is based on OpenWeatherMap (@csparpa, pyowm) to develop.

null 11 Sep 30, 2022
Weather Tracker, made with Python using Open Weather API

Weather Tracker Weather Tracker, made with Python using Open Weather API

Sahil Kumar 1 Feb 7, 2022
Visual Weather api. Returns beautiful pictures with the current weather.

VWapi Visual Weather api. Returns beautiful pictures with the current weather. Installation: sudo apt update -y && sudo apt upgrade -y sudo apt instal

Hotaru 33 Nov 13, 2022
Insane Weather Bot is here! Give suggestions, fork, and do much more to help us enhance the abilities of Insane Weather Bot.

Insane_Weather_Bot Insane Weather Bot is here! Give suggestions, fork, and do much more to help us enhance the abilities of Insane Weather Bot. Weathe

null 1 Jan 2, 2022
Python wrapper library for World Weather Online API

pywwo Python wrapper library for World Weather Online API using lxml.objectify How to use from pywwo import * setKey('<your_key>', 'free') w=LocalWeat

World Weather Online 20 Dec 19, 2022
Generate direct m3u playlist for all the channels subscribed in the Tata Sky portal

Tata Sky IPTV Script generator A script to generate the m3u playlist containing direct streamable file (.mpd or MPEG-DASH or DASH) based on the channe

Gaurav Thakkar 250 Jan 1, 2023
Techie Sneh 19 Dec 3, 2021
Chronocalc - Calculates the dates and times when the sun or moon is in a given position in the sky

Chronocalc I wrote this script after I was busy updating my article on chronoloc

null 16 Dec 13, 2022
🚀 An asynchronous python API wrapper meant to replace discord.py - Snappy discord api wrapper written with aiohttp & websockets

Pincer An asynchronous python API wrapper meant to replace discord.py ❗ The package is currently within the planning phase ?? Links |Join the discord

Pincer 125 Dec 26, 2022
Surfline Forecast Bot For Python

Surfline Forecast Bot A telegram bot created using Telethon that allows users to

null 1 May 8, 2022
Change between dark/light mode depending on the ambient light intensity

svart Change between dark/light mode depending on the ambient light intensity Installation Install using pip $ python3 -m pip install --user svart Ins

Siddharth Dushantha 169 Nov 26, 2022
Aws-lambda-requests-wrapper - Request/Response wrapper for AWS Lambda with API Gateway

AWS Lambda Requests Wrapper Request/Response wrapper for AWS Lambda with API Gat

null 1 May 20, 2022
Weather App using openweathermap API

This is my hobby project used to learn how to use public api for project.In this i used the api of openweathermap to featch the weather details of various city across the globe by giving city name as input.

Subramanya K S 1 Nov 6, 2021
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
Python API wrapper around Trello's API

A wrapper around the Trello API written in Python. Each Trello object is represented by a corresponding Python object. The attributes of these objects

Richard Kolkovich 904 Jan 2, 2023