Skip to content

Instantly share code, notes, and snippets.

@ajlee2006
Last active December 9, 2021 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajlee2006/7c3e474d0e5d2e9b5daa7fd307abef2c to your computer and use it in GitHub Desktop.
Save ajlee2006/7c3e474d0e5d2e9b5daa7fd307abef2c to your computer and use it in GitHub Desktop.
xkcd 2542 Daylight Calendar in Python

Python Daylight Calendar

As seen on xkcd

It arbitrarily counts from the start of the year you give it in UTC. You can also change the coordinates of where the sunrise and sunset API is checking.

I have found that the API has some issues, such as returning 1970-01-01 when there is no sunrise or sunset, no matter if the sun is up. It also does not work for 1970-01-01, so any 1970 date won't work in the program.

This might be outdated, I will be updating mainly on Replit https://replit.com/@AJLee/xkcdDaylightCalendar

import requests, datetime
t = datetime.datetime(2021, 11, 15, 14, 20)
print("Attempting to find", t, "in xkcd's Daylight Calendar system")
lat,lng = 51.4769,0
print("Location:", (lat,lng))
tc = datetime.datetime(t.year, 1, 1)
print("Arbitrarily starting calculation from", tc, "in UTC")
prevdaystart = tc
prevdiff = datetime.timedelta()
daylengths = []
while tc <= t:
#print("It is the start of", tc.date(), "and", len(daylengths), "days have passed.")
s = requests.get('https://api.sunrise-sunset.org/json?lat=' + str(lat) + '&lng=' + str(lng) + '&formatted=0&date=' + tc.date().isoformat()).json()["results"]
sunrise = datetime.datetime.fromisoformat(s["sunrise"]).replace(tzinfo=None)
sunset = datetime.datetime.fromisoformat(s["sunset"]).replace(tzinfo=None)
diff = sunset-sunrise + prevdiff
#print(sunrise,sunset,diff)
while diff > datetime.timedelta(hours=12):
diff -= datetime.timedelta(hours=12)
daylengths.append((sunset - diff) - prevdaystart)
prevdaystart = sunset - diff
print("It is now", prevdaystart, "and", len(daylengths), "days have passed.")
print("The previous day's length was", daylengths[-1], "or", daylengths[-1].seconds, "seconds")
prevdiff = diff
tc += datetime.timedelta(days=1)
if (t-prevdaystart).total_seconds() < 0:
print("At", t, "there have been", len(daylengths)-1, "days, and the current progress is", daylengths[-1]+t-prevdaystart, "or", (daylengths[-1]+t-prevdaystart).seconds, "seconds")
else:
print("At", t, "there have been", len(daylengths), "days, and the current progress is", t-prevdaystart, "or", (t-prevdaystart).seconds, "seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment