Properly use date and timezones
All checks were successful
docker-image / docker (push) Successful in 10m12s

This commit is contained in:
Stefan Bethke 2025-06-12 21:15:10 +02:00
commit 123803d619

View file

@ -47,32 +47,20 @@ class DBFAnimation(BubaAnimation):
def countdown(dt: datetime):
now = datetime.datetime.now().astimezone()
try:
dep_time = datetime.datetime.strptime(dt, "%H:%M").replace(tzinfo=now.tzinfo).time()
except TypeError as e:
day = now.strftime("%y-%m-%d")
departure = datetime.datetime.strptime(f"{day} {dt}", "%y-%m-%d %H:%M").astimezone()
except ValueError as e:
return "--"
# First, assume all departure times are on the current day
dep_date = now.date()
# Calculate timedelta under the above assumption
dep_td = datetime.datetime.combine(dep_date, dep_time,tzinfo=now.tzinfo) - now
LOG.info(f"Processing time {datetime.datetime.combine(dep_date, dep_time, tzinfo=now.tzinfo)}, delta {dep_td}")
# If the calculated timedelta is more than one hour in the past,
# assume that the day should actually be the next day
# (This will be the case e.g. when a train departs at 00:15 and it's currently 23:50)
dep_td = departure - now
if dep_td.total_seconds() <= -3600:
dep_date += datetime.timedelta(days=1)
# If the calculated timedelta is more than 23 hours in the future,
# assume that the day should actually be the previous day.
# (This will be the case e.g. when a train should have departed at 23:50 but it's already 00:15)
# dep_date += datetime.timedelta(days=1)
departure += datetime.timedelta(days=1)
if dep_td.total_seconds() >= 3600 * 23:
dep_date -= datetime.timedelta(days=1)
# dep_date -= datetime.timedelta(days=1)
departure -= datetime.timedelta(days=1)
# Recalculate the timedelta
return BubaAnimation.countdown(datetime.datetime.combine(dep_date, dep_time))
return BubaAnimation.countdown(departure)
@staticmethod
def short_station(station: str) -> str: