Last active
March 14, 2023 16:27
-
-
Save mattpitkin/98f029b67ab87f91c998345b442b3eed to your computer and use it in GitHub Desktop.
Plot sunrise and sunset times over a year
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
""" | |
Plot the sun rise, sunset and length of daylight hours over a year | |
(from a given location). This uses the astropy and astroplan packages. | |
""" | |
from matplotlib import pyplot as plt | |
import numpy as np | |
from astropy.time import Time, TimeDelta | |
from astropy import units as u | |
from astroplan import Observer | |
# set location | |
lat = 52.178731 * u.deg | |
long = 0.222518 * u.deg | |
obs = Observer(latitude=lat, longitude=long) | |
# time steps of a day | |
dt = TimeDelta(1 * u.day) | |
# start date/time | |
starttime = Time("2022-01-01 12:00:00", scale="utc") | |
sunrise = [] | |
sunset = [] | |
for i in range(365): | |
# get sunrise time | |
srd = obs.sun_rise_time(starttime, which="previous").jd - 0.5 | |
srd = 24 * (srd - int(srd)) # get hour in day | |
sunrise.append(srd) | |
# get sunset time | |
ssd = obs.sun_set_time(starttime, which="next").jd - 0.5 | |
ssd = 24 * (ssd - int(ssd)) | |
sunset.append(ssd) | |
starttime += dt | |
fig, ax = plt.subplots(figsize=(8, 4)) | |
ax.plot(range(365), sunrise, label="Sun rise") | |
ax.plot(range(365), sunset, label="Sun set") | |
ax.plot(range(365), np.asarray(sunset) - np.asarray(sunrise), label="Length of day") | |
ax.set_xlabel("Day") | |
ax.set_ylabel("Time (hours)") | |
ax.legend() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment