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)
Easy to use API Wrapper for somerandomapi.ml.

Overview somerandomapi is an API Wrapper for some-random-api.ml Examples Asynchronous from somerandomapi import Animal import asyncio async def main

Myxi 1 Dec 31, 2021
A python based all-in-one tool for Google Drive

gdrive-tools A python based all-in-one tool for Google Drive Uses For Gdrive-Tools ✓ generate SA ✓ Add the SA and Add them to TD automatically ✓ Gener

XcodersHub 32 Feb 09, 2022
Mikasa is a 100% Spanish bot, a multifunctional bot, Mikasa is in beta.

Mikasa Miaksa, It is a multi-functional discord bot that is currently in development, this is not complete, there are still many things to fix and imp

Made in 2 Oct 05, 2021
A Telegram bot for Download songs in mp3 format from YouTube and Extract lyrics from Genius.com ❤️

MeudsaMusic A Telegram bot for Download songs in mp3 format from YouTube and Extract lyrics from Genius.com ❤️ Commands Reach @MedusaMusic on Telegram

Bibee 14 Oct 06, 2022
Grape - A webbrowser with its own Search Engine

Grape 🔎 A Web Browser made entirely in python. Search Engine 🔎 Installation: F

Grape 2 Sep 06, 2022
A Discord bot that rewards players in Minecraft for sending messages on Discord

MCRewards-Discord-Bot A Discord bot that rewards players in Minecraft for sending messages on Discord How to setup: Download this git as a .zip, or cl

3 Dec 26, 2021
Isobot is originally made by notsniped. This is a remix of iso.bot by archisha.

iso6.9-1.2beta iso.bot is originally made by notsniped#0002. This is a remix of iso.bot by αrchιshα#5518. iso6.9 is a Discord bot written in Python an

Kamilla Youver 3 Jan 11, 2022
Luna Rush Auto Clicker Bot

Luna Rush Auto Clicker Bot Se o aplicativo lhe ajudar de alguma forma, uma doação para ajudar a pagar a conta de luz sempre é bem vinda ;) Wallet Smar

Walter Discher Cechinel 29 Dec 20, 2022
The program for obtaining a horoscope in Python using API from rapidapi.com site.

Python horoscope The program allows you to get a horoscope for your zodiac sign and immediately translate it into almost any language. Step 1 The firs

Architect 0 Dec 25, 2021
ALIEN: idA Local varIables rEcogNizer

ALIEN: idA Local varIables rEcogNizer ALIEN is an IDA Pro plugin that allows the user to get more information about ida local variables with the help

16 Nov 26, 2022
Django3 web app that renders OpenWeather API data ☁️☁️

nz-weather For a live build, visit - https://brandonru.pythonanywhere.com/ NZ Openweather API data rendered using Django3 and requests ☀️ Local Run In

Brandon Ru 1 Oct 17, 2021
A twitter multi-tool for OSINT on twitter accounts.

TwitterCheckr A twitter multi-tool for OSINT on twitter accounts. Infomation TwitterCheckr also known as TCheckr is multi-tool for OSINT on twitter a

IRIS 16 Dec 23, 2022
Ethereum Gas Fee for the MacBook Pro touchbar (using BetterTouchTool)

Gasbar Ethereum Gas Fee for the MacBook Pro touchbar (using BetterTouchTool) Worried about Ethereum gas fees? Me too. I'd like to keep an eye on them

TSS 51 Nov 14, 2022
Python wrapper for GitHub API v3

Squeezeit - Python CSS and Javascript minifier Copyright (C) 2011 Sam Rudge This program is free software: you can redistribute it and/or modify it un

David Medina 207 Oct 24, 2022
Discord heximals: More colors for your bot

DISCORD-HEXIMALS More colors for your bot ! Support : okimii#0434 COLORS ( 742 )

4 Feb 04, 2022
A Python SDK for Tinybird 🐦

Verdin Verdin is a tiny bird, and also a Python SDK for Tinybird . Install pip install verdin Usage Query a Pipe # the tinybird module exposes all im

LocalStack 13 Dec 14, 2022
BanAllBot - Telegram Code To Ban All Group Members very fast

BanAllBot Telegram Code To Ban All Group Members very fast FORK AND KANG WITH CR

27 May 13, 2022
A Simple Voice Music Player

📀 𝐕𝐂𝐔𝐬𝐞𝐫𝐁𝐨𝐭 √𝙏𝙚𝙖𝙢✘𝙊𝙘𝙩𝙖𝙫𝙚 NOTE JUST AN ENGLISH VERSION OF OUR PRIVATE SOURCE WAIT FOR LATEST UPDATES JOIN @𝐒𝐔𝐏𝐏𝐎𝐑𝐓 JOIN @𝐂?

TeamOctave 8 May 08, 2022
An EmbedBuilder for Discord bots in Python.

An EmbedBuilder for Discord bots in Python. You need discord.py to use this module.

6 Jan 13, 2022
Music bot for playing music on telegram voice chat group.

Somali X Music 🎵 Music bot for playing music on telegram voice chat group. Requirements FFmpeg NodeJS nodesource.com Python 3.8+ or Higher PyTgCalls

Abdisamad Omar Mohamed 4 Dec 01, 2021