My code style is ugly. But here's my Python program I wrote with your valuable assistance. Please don't laugh.
P.S. It won't run as pasted below because my mail client throws away the tabs.
One question I have yet to answer: Checking the answers against a web site, it seems like it's correcting for DST, but it's not supposed to. The docs say it won't. That's why I put the "is_dst" function in; I was expecting to have to compensate by an hour if DST is true. But DST comes back True (at the moment) and the times are correct.
I guess I'll have to revisit in the fall after DST.
#!/usr/bin/python
# Return times for dawn, sunrise, dusk, sunset, etc.
# Note: most python libs for getting your timezone get a tuple with local zone names, like "CST, CDT" which
# the astral.sun package can't handle. What you need is the IANA timezone name, like "US/Chicago" or "US/Central"
import sys, os, getopt
import pytz
from astral import LocationInfo
from astral.sun import sun
from datetime import date, datetime, timezone, timedelta
import time
import tzlocal
ver = "2.3"
# My house in Waukesha County (Original has many more decimals)
mylat = 43.1
mylon = -88.1
# These are the formats for dates/times with and without -v (verbose) option.
longfmt ="%Y-%m-%d %H:%M:%S.%f"
shortfmt="%H:%M:%S"
# ================================================================================
def usage():
print(me,ver)
print("Get and display times of local dawn, sunrise, noon, dusk, sunset.")
print("Times are based on a fixed longitude and latitude, hardcoded.")
print("Options:")
print(" -h Help")
print(" -v Verbose output / debugging")
print(" -d Show time of local Dawn")
print(" -s Sunrise")
print(" -n Noon (or -N)")
print(" -S Sunset")
print(" -D Dusk")
print(" -L Location information (or -l)")
print(" -t Time & date information")
print(" -T Time Zone information")
print(" -y Daylight Saving Time Status")
print()
print("NOTE: If multiple options are given, the times are printed in the order the events occur:")
print("Dawn, Sunrise, Noon, Sunset, Dusk")
print()
# ================================================================================
def is_dst(dt=None, timezone='UTC'):
"""Is daylight savings in effect?"""
if dt is None:
dt = datetime.datetime.utcnow()
timezone = pytz.timezone(timezone)
timezone_aware_date = timezone.localize(dt, is_dst=None)
return timezone_aware_date.tzinfo._dst.seconds != 0
# ================================================================================
# PrintSunTime from dictionary s using key
def prst(k):
if oVerb == True:
print(k,"\t",s[k].strftime(longfmt)[:-4],sep='')
else:
print(s[k].strftime(shortfmt))
# ================================================================================
me = os.path.basename(sys.argv[0])
# Get argument list from command line and strip off the first one (it's the program name)
argList = sys.argv[1:]
#print("Options:",len(sys.argv))
if len(sys.argv) < 2:
print("Must enter at least one option.")
print()
usage()
sys.exit(2)
# Set options allowed on command line
options = "HhVvDdLlNnSsTty"
# ================================================================================
# Parse all the command line options
oDawn=False
oVerb=False
oDebg=False
oRise=False
oNoon=False
oSet=False
oDusk=False
oLoc=False
oTime=False
oZone=False
oDST=False
try:
opts, leftovers = getopt.getopt(argList,options)
except getopt.GetoptError as err:
print(str(err))
print()
usage()
sys.exit(3)
for opt,arg in opts:
if oDebg == True:
print("opt =",opt,"\t","arg =",arg)
if opt in ("-h","-H"):
usage()
sys.exit(0)
if opt in ("-d"):
oDawn = True
if opt in ("-s"):
oRise = True
if opt in ("-n","-N"):
oNoon = True
if opt in ("-S"):
oSet = True
if opt in ("-D"):
oDusk = True
if opt in ("-l","-L"):
oLoc = True
if opt in ("-t"):
oTime = True
if opt in ("-T"):
oZone = True
if opt in ("-v"):
oVerb=True
if opt in ("-V"):
oDebg=True
if opt in ("-y"):
oDST=True
# ================================================================================
if oDebg == True:
print("oDawn\toVerb\toDebg\toRise\toNoon\toSet\toDusk\toLoc\toTime\toZone\toDST")
print(oDawn,oVerb,oDebg,oRise,oNoon,oSet,oDusk,oLoc,oTime,oZone,oDST,sep="\t")
print()
print("opts:",opts,"\t","Leftovers:",leftovers)
# ================================================================================
mynow = datetime.today()
myyear = mynow.year
mymon = mynow.month
mydate = mynow.day
myhour = mynow.hour
mymin = mynow.minute
mysec = mynow.second
# This value is not useful
mytz = time.tzname
# This value is the IANA timezone name we need.
tziana=tzlocal.get_localzone_name()
# Determine if we're in daylight saving time now:
isdst = is_dst(mynow, timezone=tziana)
if oTime == True:
print(f"{myyear}-{mymon:02d}-{mydate:02d}\t{myhour:02d}:{mymin:02d}:{mysec:02d}")
if oZone == True:
print("timezone:",mytz,"\t", "IANA Timezone:",tziana,"\t","Is DST now:",isdst)
if oDST == True:
print("DST: ",isdst)
# ================================================================================