Created
October 30, 2020 08:06
-
-
Save msafadieh/a7d86d756f6fdb6a87e58aec207073c3 to your computer and use it in GitHub Desktop.
find out if it's daytime using GPS coordinates and no external libraries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
small function needed for a personal project of mine | |
""" | |
from datetime import datetime, timezone | |
import json | |
from urllib.parse import urlencode | |
from urllib.request import urlopen | |
# lat and lng can be int, float, or strings. wooo dynamic typing! | |
def is_daytime(lat, lng): | |
# 'formatted: 0' will return the result in ISO format | |
params = urlencode({"lat": lat, "lng": lng, "formatted": 0}) | |
url = "https://api.sunrise-sunset.org/json?{}".format(params) | |
with urlopen(url) as f: | |
response = json.load(f) | |
if response["status"] == "OK": | |
sunrise = datetime.fromisoformat(response["results"]["sunrise"]) | |
sunset = datetime.fromisoformat(response["results"]["sunset"]) | |
# fun fact, did u know that datetime.utcnow() returns datetime objects | |
# that are not timezone aware? | |
now = datetime.now(timezone.utc) | |
# if it's past sunrise then it's night. if it's after sunrise but before sunset then it's day. | |
return (now >= sunrise and now < sunset) or not (now < sunrise) | |
raise Exception("API Error") | |
# Gorham, ME | |
print(is_daytime("43.679531", "-70.444221")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment