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)


    [email protected] ~ $ 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)
Fully asynchronous trace.moe API wrapper

AioMoe Fully asynchronous trace.moe API wrapper Installation You can install the stable version from PyPI: $ pip install aiomoe Or get it from github

2 Jun 26, 2022
TG-Streaming-bot - TG Simple Streaming bot

TG Simple Streaming bot telegram video straming bot 🎚️ Features Play youtube li

HyDrix 4 May 05, 2022
This is a discord bot, which tells you food recipes.

Discord Chef Bot You have a friend, familiy or other group / channel where the topic is the food? You cannot really decide what's for Saturday lunch?

2 Apr 25, 2022
Monitor robot of Apple Store's products, using DingTalk notification.

概述 本项目应用主要用来监测Apple Store线下直营店货源情况,主要使用Python实现。 首先感谢iPhone-Pickup-Monitor项目带来的灵感,同时有些实现也直接使用了该项目的一些代码。 本项目在iPhone-Pickup-Monitor原有功能的基础上去掉了声音通知,但添加了多

Lennon Chin 159 Dec 09, 2022
SSH-Restricted deploys an SSH compliance rule (AWS Config) with auto-remediation via AWS Lambda if SSH access is public.

SSH-Restricted SSH-Restricted deploys an SSH compliance rule with auto-remediation via AWS Lambda if SSH access is public. SSH-Auto-Restricted checks

Adrian Hornsby 30 Nov 08, 2022
AWS Enumeration and Footprinting Tool

Quiet Riot 🎶 C'mon, Feel The Noise 🎶 An enumeration tool for scalable, unauthenticated validation of AWS principals; including AWS Acccount IDs, roo

Wes Ladd 89 Jan 05, 2023
Visualize size of directories, s3 buckets.

Dir Sizer This is a work in progress, right now consider this an Alpha or Proof of Concept level. dir_sizer is a utility to visualize the size of a di

Scott Seligman 13 Dec 08, 2022
A Simple Advance Auto Filter Bot Complete Rewritten Version Of Adv-Filter-Bot

Adv Auto Filter Bot This Is Just An Simple Advance Auto Filter Bot Complete Rewritten Version Of Adv-Filter-Bot.. Just Sent Any Text As Query It Will

TeamShadow 4 Dec 10, 2021
A Discord bot written in Python to help with guild administration

forgotten-hydra A Discord bot written in Python to help with guild administration. External libraries Pycord-Development/pycord 1.7.3 djc/couchdb-pyth

1 May 14, 2022
SmsSender v3.0.0 - the script is designed to send free SMS to any number and with any text.

SmsSender v3.0.0 - скрипт предназначен для бесплатной отправки SMS на любой номер и с любым текстом. Возможны небольшие баги, в скором времени исправл

Андрей Сергеев 20 Dec 03, 2021
A Twitter bot written in Python using Tweepy and hosted on a server.

A Twitter bot written in Python using Tweepy. It can like and/or retweet tweets that contain single or multiple keywords and hashtags.

anniedotexe 11 Dec 15, 2022
A cut down version of QUANT containing just the model in Python (QUANTPy)

A cut down version of QUANT containing just the model in Python (QUANTPy)

2 Apr 15, 2022
A discord token grabber made in Python 3

Discord Token Grabber A Discord token grabber written in Python 3. This version of the grabber only supports Windows. Features Transfers via Discord w

Mega145 4 Aug 04, 2022
Alcarin Tengwar - a Tengwar typeface designed to pair well with the Brill typeface

Alcarin Tengwar Alcarin Tengwar is a Tengwar typeface designed to pair well with

Toshi Omagari 23 Nov 02, 2022
An open source, multipurpose, configurable discord bot that does it all

Spacebot - Discord Bot Music, Moderation, Fun, Utilities, Games and Fully Configurable. Overview • Contributing • Self hosting • Documentation (not re

Dhravya Shah 41 Dec 10, 2022
Drop-in Replacement of pychallonge

pychal Pychal is a drop-in replacement of pychallonge with some extra features and support for new Python versions. Pychal provides python bindings fo

ZED 29 Nov 28, 2022
A modular dynamical-systems model of Ethereum's validator economics.

CADLabs Ethereum Economic Model A modular dynamical-systems model of Ethereum's validator economics, based on the open-source Python library radCAD, a

CADLabs 104 Jan 03, 2023
dex.guru python sdk

dexguru-sdk.py dexguru-sdk.py allows you to access dex.guru public methods from your async python scripts. Installation To install latest version, jus

DexGuru 17 Dec 06, 2022
Scanner and Checker for Binance Scam Contracts

Money Printer by Warranty Voider well this isnt exactly a printer, but it helps you find and check new token startups. In the end its a nice scam cont

12 Nov 24, 2022
A Python Module That Uses ANN To Predict A Stocks Price And Also Provides Accurate Technical Analysis With Many High Potential Implementations!

Stox ⚡ A Python Module For The Stock Market ⚡ A Module to predict the "close price" for the next day and give "technical analysis". It uses a Neural N

Dopevog 31 Dec 16, 2022