Files
weather-info/app/utils/time_utils.py
2025-11-19 08:31:16 +00:00

137 lines
3.4 KiB
Python

import time
import ntptime # type: ignore
_UTC_OFFSET: int = 1 * 3600 # +1 or +2 hours for CEST, adjust for your timezone
def local_time_with_offset() -> int:
# Set timezone offset (in seconds)
current_time = time.time() + _UTC_OFFSET
return time.localtime(current_time)
def get_datetime_string(format="full") -> str:
"""
Return date/time as string with different formats
Args:
format: "full", "date", "time", "short", "ticks"
"""
try:
year, month, day, hour, minute, second, weekday, yearday = (
local_time_with_offset()
)
if format == "full":
return (
f"{year:04d}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
)
elif format == "date":
return f"{year:04d}-{month:02d}-{day:02d}"
elif format == "time":
return f"{hour:02d}:{minute:02d}:{second:02d}"
elif format == "short":
return f"{month:02d}/{day:02d} {hour:02d}:{minute:02d}"
else:
return f"Ticks: {time.ticks_ms()} ms"
except:
return f"Ticks: {time.ticks_ms()} ms"
def get_german_datetime() -> str:
"""Return German date and time"""
try:
year, month, day, hour, minute, second, weekday, yearday = (
local_time_with_offset()
)
weekdays = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
weekday_name = weekdays[weekday]
return f"{weekday_name}.{day:02d}.{month:02d}.{year} {hour:02d}:{minute:02d}"
except:
ticks = time.ticks_ms() // 1000
return f"Zeit: {ticks} sek"
def get_german_timestamp_short() -> str:
"""Get German timestamp with short months (for Wokwi)"""
ticks = time.ticks_ms()
day = (ticks // 86400000) % 31 + 1
month = (ticks // 2592000000) % 12 + 1
hour = (ticks // 3600000) % 24
minute = (ticks // 60000) % 60
months = [
"Jan",
"Feb",
"Mär",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez",
]
month_name = months[month - 1]
return f"{day}.{month_name} {hour:02d}:{minute:02d}"
def get_german_time_ticks() -> str:
"""Get German time using ticks (works in Wokwi)"""
ticks = time.ticks_ms()
# Simulate time progression
total_seconds = ticks // 1000
hours = (total_seconds // 3600) % 24
minutes = (total_seconds // 60) % 60
seconds = total_seconds % 60
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def get_german_date_ticks() -> str:
"""Get German date using ticks"""
ticks = time.ticks_ms()
# Simulate date progression (starting from Jan 15, 2024)
days_passed = ticks // (24 * 3600 * 1000)
day = 15 + (days_passed % 28) # Simple month simulation
month = 1 + (days_passed // 28) % 12
year = 2024 + (days_passed // (28 * 12))
months = [
"JAN",
"FEB",
"MAR",
"APR",
"MAI",
"JUN",
"JUL",
"AUG",
"SEP",
"OKT",
"NOV",
"DEZ",
]
month_name = months[month - 1]
return f"{day:02d}.{month_name}.{str(year)[-2:]}"
def sync_ntp_time() -> bool:
try:
print("Syncing time via NTP...")
ntptime.settime() # Default uses pool.ntp.org
print("Time synchronized successfully!")
return True
except Exception as e:
print("NTP sync failed:", e)
return False