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)
API which uses discord+mojang api to scrape NameMC searches/droptime/dropping status of minecraft names, and texture links

API which uses discord+mojang api to scrape NameMC searches/droptime/dropping status of minecraft names, and texture links

2 Dec 22, 2021
Price checker windows application

Price-Checker price checker windows application This application monitors the prices of selected products and displays a notification if the price has

Danila Tsareff 1 Nov 29, 2021
Most Simple & Powefull web3 Trade Bot (WINDOWS LINUX) Suport BSC ETH

Most Simple & Powefull Trade Bot (WINDOWS LINUX) What Are Some Pros And Cons Of Owning A Sniper Bot? While having a sniper bot is typically an advanta

GUI BOT 6 Jan 30, 2022
Telegram bot for searching videos in your PDisk account by @AbirHasan2005

PDisk-Videos-Search A Telegram bot for searching videos in your PDisk account by @AbirHasan2005. Configs API_ID - Get from @TeleORG_Bot API_HASH - Get

Abir Hasan 39 Oct 21, 2022
RichWatch is wrapper around AWS Cloud Watch to display beautiful logs with help of Python library Rich.

RichWatch is TUI (Textual User Interface) for AWS Cloud Watch. It formats and pretty prints Cloud Watch's logs so they are much more readable. Because

21 Jul 25, 2022
Kang Sticker bot

Kang Sticker Bot A simple Telegram bot which creates sticker packs from other stickers, images, documents and URLs. Based on kangbot Deploy Credits: s

Hafitz Setya 11 Jan 02, 2023
Azure Neural Speech Service TTS

Written in Python using the Azure Speech SDK. App.py provides an easy way to create an Text-To-Speech request to Azure Speech and download the wav file. Azure Neural Voices Text-To-Speech enables flu

Rodney 4 Dec 14, 2022
A tool written in Python used to instalock agents in VALORANT using the local API.

Valorant Instalock Tool v2.1.0 by Mr. SOSA A tool written in Python used to instalock agents in VALORANT using the local API. This is NOT a hotkey pro

Mr. SOSA 3 Nov 18, 2021
Trading bot rienforcement with python

Trading_bot_rienforcement System: Ubuntu 16.04 GPU (GeForce GTX 1080 Ti) Instructions: In order to run the code: Make sure to clone the stable baselin

1 Oct 22, 2021
Scrape the Twitter Frontend API without authentication.

Twitter Scraper 🇰🇷 Read Korean Version Twitter's API is annoying to work with, and has lots of limitations — luckily their frontend (JavaScript) has

Buğra İşgüzar 3.4k Jan 08, 2023
A minimal caching proxy to GitHub's REST & GraphQL APIs

github-proxy A caching forward proxy to GitHub's REST and GraphQL APIs. GitHub-Proxy is a thin, highly extensible, highly configurable python framewor

Babylon Health 26 Oct 05, 2022
a discord bot that pulls the latest or most relevant research papers from arxiv.org

AI arxiver a discord bot that pulls the latest or most relevant research papers from arxiv.org invite link : Arxiver bot link works in progress Usage

Ensias AI 14 Sep 03, 2022
Fastest Tiktok Username checker on site.

Tiktok Username Checker Fastest Tiktok Username checker on site

sql 3 Jun 19, 2021
Checks instagram names to see if they're available

How to install You must have python 3.7.6 installed and make sure you click the 'ADD TO PATH' option when installing Open cmd and type pip install aio

2 Oct 20, 2021
Repositorio que contiene el material mostrado en la primera PyCON de Chile

Buenas prácticas de desarrollo en Python Repositorio que contiene el material mostrado en la primera PyCON de Chile, realizada del 5 al 7 de Noviembre

Erick Castillo 5 Feb 01, 2022
Discord-Bot - Bot using nextcord for beginners

Discord-Bot Bot using nextcord for beginners! Requirements: 1 :- Install nextcord by typing "pip install nextcord" Thats it! You can use this code any

INFINITE_. 3 Jan 10, 2022
Async ready API wrapper for Revolt API written in Python.

Mutiny Async ready API wrapper for Revolt API written in Python. Installation Python 3.9 or higher is required To install the library, you can just ru

16 Mar 29, 2022
An Anime Theme Telegram group management bot. With lot of features.

Emilia Project Emilia-Prjkt is a modular bot running on python3 with anime theme and have a lot features. Easiest Way To Deploy On Heroku This Bot is

ZenitsuID #M•R•T™ 3 Feb 03, 2022
A discord token nuker With loads of options that will screw an account up real bad, also has inbuilt massreport, GroupChat Spammer and Token/Password/Creditcard grabber and so much more!

Installation | Important | Changelogs | Discord NOTE: Hazard is not finished! You can expect bugs, crashes, and non-working functions. Please make an

Rdimo 470 Aug 09, 2022
A Python Library to interface with Flickr REST API, OAuth & JSON Responses

Python-Flickr Python-Flickr is A Python library to interface with Flickr REST API & OAuth Features Photo Uploading Retrieve user information Common Fl

Mike Helmick 40 Sep 25, 2021