Sunrise and Sunset

This Sunrise and Sunset API will return interesting data about the day like: sunset, sunrise, day length, nautical twilight, civil twilight and astronomical twilight. One thing to be careful about is times will be GMT so depending on the location you’re looking up you might want to adjust the times returned.

Here is a simply code that uses requests, json and webbrowser libraries harmoniously.

Code below demonstrates a simple API query based on Central Park coordinates in New York and date of November 27 2019.

import requests
import json
import webbrowser
params = {"lat":40.779659, "lng":-73.968995, "date":"2019-11-27"}

f = r"https://api.sunrise-sunset.org/json?"

def sunrisesunset(f):
    a = requests.get(f, params=params)
    a = json.loads(a.text)
    a = a["results"]
    return (a["sunrise"], a["sunset"], a["day_length"])

print(sunrisesunset(f))

Output example:

Central Park, New York

November 27, 2019

Sunrise

6 am
hour
57
minute
1
second

Sunset

4 pm
hour
30
minute
1
second

Day Length

9
hour
33
minute
1
second

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

Source of API: Sunrise and Sunset API

Recommended Posts