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)
SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

Jeeck X Nano 1 Dec 27, 2021
Unfollows Users You're Following

Github-Unfollow-Bot Info It unfollows users you're following, it runs in the background so you can still do what you do without it bothering you. It's

ExT 4 Sep 03, 2022
Use GitHub Actions to create a serverless service.

ActionServerless - Use GitHub Actions to create a serverless service ActionServerless is an action to do some computing and then generate a string/JSO

107 Oct 28, 2022
Kyura-Userbot: a modular Telegram userbot that runs in Python3 with a sqlalchemy database

Kyura-Userbot Telegram Kyura-Userbot adalah userbot Telegram modular yang berjal

Kyura 17 Oct 29, 2022
ML-Test-Client

ML-Test-Client Introduction What is this? This Test Client App is to be used to crowd-test machine learning models with the goal of finding the best c

11 Jul 15, 2022
QR login for pyrogram client

Generate Pyrogram session via QRlogin

ポキ 18 Oct 21, 2022
Telegram bot for logistic - Telegram bot for logistic

Демонстрационный телеграм-бот для нужд транспортной компании Цель проекта Реализ

M1chigun 1 Feb 05, 2022
A reddit bot that imitates the popular reddit bot "u/repostsleuthbot" to trick people into clicking on a rickroll

Reddit-Rickroll-Bot A reddit bot that imitates the popular reddit bot "u/repostsleuthbot" to trick people into clicking on a rickroll Made with The Py

0 Jul 16, 2022
⚔️ Fastest tibia bot API

📝 Description tibia bot api using python ⌨ Development ⚙ Running the app python bot.py ✅ ROADMAP Add confidence to floor level to have more accuracy

Lucas Santos 133 Dec 28, 2022
Isobot is originally made by notsniped. This is a remix of iso.bot by archisha.

iso6.9-08122021b-1.2beta Isobot is originally made by notsniped#0002. This is a remix of iso.bot by αrchιshα#5518. isobot6.9 is a Discord bot written

Kamilla Youver 3 Jan 11, 2022
A telegram bot to forward messages automatically when they arrived.

Telegram Message Forwarder Bot A telegram bot, which can forward messages from channel, group or chat to another channel, group or chat automatically.

Adnan Ahmad 181 Jan 07, 2023
A simple Python library to integrate with the Heron Data API

Heron Python This library provides easy access to the Heron Data API from applications written in Python. Documentation No language-specific docs are

Heron Data 11 Nov 11, 2022
A modular telegram Python bot running on python3 with an sqlalchemy database.

TG_Bot A modular telegram Python bot running on python3 with an sqlalchemy database. Originally a simple group management bot with multiple admin feat

Movindu Bandara 1 Nov 02, 2021
A minimalist file manager for those who want to use Linux mobile devices.

Portfolio A minimalist file manager for those who want to use Linux mobile devices. Usage Tap to activate and press to select, to browse, open, copy,

Martin Abente Lahaye 71 Nov 18, 2022
Me and @nathanmargni did a small analysis on what are the best strategies to win more games of League of Legends.

Me and @nathanmargni did a small analysis on what are the best strategies to win more games of League of Legends.

Christian Berchtold 2 Jan 19, 2022
Declarative assertions for AWS

AWSsert AWSsert is a Python library providing declarative assertions about AWS resources to your tests. Installation Use the package manager pip to in

19 Jan 04, 2022
Quack-SMS-BOMBER - Quack Toolkit By IkigaiHack

Quack Toolkit By IkigaiHack About Quack Toolkit Quack Toolkit is a set of tools

Marcel 2 Aug 19, 2022
Automatic SystemVerilog linting in github actions with the help of Verible

Verible Lint Action Usage See action.yml This is a GitHub Action used to lint Verilog and SystemVerilog source files and comment erroneous lines of co

CHIPS Alliance 10 Dec 26, 2022
Template to create a telegram bot in python

Template for Telegram Bot Template to create a telegram bot in python. How to Run Set your telegram bot token as environment variable TELEGRAM_BOT_TOK

PyTopia 10 Mar 07, 2022
New developed moderation discord bot by archisha

Monitor42 New developed moderation discord bot by αrchιshα#5518. Details Prefix: 42! Commands: Moderation Use 42!help to get command list. Invite http

Kamilla Youver 0 Jun 29, 2022