83 lines
2.1 KiB
Python
83 lines
2.1 KiB
Python
"""
|
|
Timezone utilities for CEST/CET conversion
|
|
"""
|
|
from datetime import datetime, timezone
|
|
import pytz
|
|
|
|
def get_cest_timezone():
|
|
"""Get CEST/CET timezone (Europe/Berlin)"""
|
|
return pytz.timezone('Europe/Berlin')
|
|
|
|
def get_server_timezone():
|
|
"""Get server's local timezone (IST)"""
|
|
return pytz.timezone('Asia/Kolkata')
|
|
|
|
def utc_to_cest(utc_datetime):
|
|
"""
|
|
Convert UTC datetime to CEST/CET timezone
|
|
|
|
Args:
|
|
utc_datetime: UTC datetime object
|
|
|
|
Returns:
|
|
datetime object in CEST/CET timezone
|
|
"""
|
|
if utc_datetime is None:
|
|
return None
|
|
|
|
# Ensure the datetime is timezone-aware
|
|
if utc_datetime.tzinfo is None:
|
|
utc_datetime = utc_datetime.replace(tzinfo=timezone.utc)
|
|
|
|
cest_tz = get_cest_timezone()
|
|
return utc_datetime.astimezone(cest_tz)
|
|
|
|
def local_to_cest(local_datetime):
|
|
"""
|
|
Convert local server time (IST) to CEST/CET timezone
|
|
|
|
Args:
|
|
local_datetime: Local datetime object (from server)
|
|
|
|
Returns:
|
|
datetime object in CEST/CET timezone
|
|
"""
|
|
if local_datetime is None:
|
|
return None
|
|
|
|
# First, make the local datetime timezone-aware
|
|
ist_tz = get_server_timezone()
|
|
if local_datetime.tzinfo is None:
|
|
local_datetime = ist_tz.localize(local_datetime)
|
|
|
|
# Convert to CEST/CET
|
|
cest_tz = get_cest_timezone()
|
|
return local_datetime.astimezone(cest_tz)
|
|
|
|
def format_cest_datetime(utc_datetime, format_str="%Y-%m-%d %H:%M:%S"):
|
|
"""
|
|
Format UTC datetime to CEST/CET timezone string
|
|
|
|
Args:
|
|
utc_datetime: UTC datetime object
|
|
format_str: Format string for datetime
|
|
|
|
Returns:
|
|
Formatted string in CEST/CET timezone
|
|
"""
|
|
if utc_datetime is None:
|
|
return None
|
|
|
|
# Convert local server time to CEST/CET
|
|
cest_datetime = local_to_cest(utc_datetime)
|
|
return cest_datetime.strftime(format_str)
|
|
|
|
def now_cest():
|
|
"""
|
|
Get current time in CEST/CET timezone
|
|
|
|
Returns:
|
|
datetime object in CEST/CET timezone
|
|
"""
|
|
cest_tz = get_cest_timezone()
|
|
return datetime.now(cest_tz) |