[2025-04-14] Handle timezone correctly with zoneinfo

This commit is contained in:
Andrew Conlin 2025-04-14 18:20:48 +09:00
parent 5489c69d04
commit 7a9a9a5eb2
2 changed files with 15 additions and 8 deletions

View File

@ -2,6 +2,7 @@
<div style="visibility: hidden">
<form id="form" method="POST" action="/">
<input name="timestamp" id="timestamp" type="number"></input>
<input name="timezone" id="timezone" type="text"></input>
</form>
</div>
</html>
@ -9,10 +10,14 @@
window.onload = function(e){
var d = new Date();
var timestamp = Math.round(d.getTime() / 1000);
input = document.getElementById("timestamp")
input.value = timestamp;
var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
ts = document.getElementById("timestamp")
ts.value = timestamp;
tz = document.getElementById("timezone")
tz.value = timezone;
form = document.getElementById("form")
form.submit();
console.log(timestamp);
console.log(timezone);
}
</script>

View File

@ -1,5 +1,6 @@
import datetime
import math
from zoneinfo import ZoneInfo
from flask import Flask, render_template, url_for, request
app = Flask(__name__)
@ -174,12 +175,12 @@ def getHomoSapiens(yearPercent):
else:
return f"Homo Sapiens have been around for ~{-math.floor(yearsUntilHumans)} years"
def getTemplate(timestamp):
now = datetime.datetime.fromtimestamp(timestamp)
def getTemplate(timestamp,timezone):
now = datetime.datetime.fromtimestamp(timestamp).astimezone(ZoneInfo(timezone))
nowTime = now.strftime("%-I:%M%p")
nowDate = now.strftime("%A") + " " + now.strftime("%-d") + " " + now.strftime("%B")
delta = now - datetime.datetime(day=1,month=1,year=now.year)
delta = now - datetime.datetime(day=1,month=1,year=now.year).astimezone(now.tzinfo)
totalDays = datetime.datetime(day=1,month=1,year=now.year+1) - datetime.datetime(day=1,month=1,year=now.year)
yearPercent = delta/totalDays
@ -193,8 +194,8 @@ def getTemplate(timestamp):
return now.year, nowTime, nowDate, round(yearPercent*100,2), footballMinute, workDay, workTime, marathonMile, abbeyRoadSong, hobbitChapter, lat, long, homoSapiens
def index(timestamp):
year, nowTime, nowDate, yearPercent, footballMinute, workDay, workTime, marathonMile, abbeyRoadSong, hobbitChapter, lat, long, homoSapiens = getTemplate(timestamp)
def index(timestamp,timezone):
year, nowTime, nowDate, yearPercent, footballMinute, workDay, workTime, marathonMile, abbeyRoadSong, hobbitChapter, lat, long, homoSapiens = getTemplate(timestamp,timezone)
cssPath = url_for("static", filename="style.css")
return render_template("index.html",\
cssPath=cssPath,\
@ -216,7 +217,8 @@ def index(timestamp):
def init():
if request.method == "POST":
timestamp = int(request.values.get('timestamp'))
return index(timestamp)
timezone = request.values.get('timezone')
return index(timestamp,timezone)
else:
return render_template("init.html")