Files
poona-ams/backend/app/core/time_utils.py
T

94 lines
2.7 KiB
Python

import calendar
from datetime import date, datetime, timezone
import json
import pytz
KOLKATA = pytz.timezone("Asia/Kolkata")
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def _read_demo_date_from_db(db) -> date | None:
from ..models.masters import Setting
row = db.query(Setting).filter(Setting.key == "demo_as_of_date").first()
if row and row.value_json:
val = json.loads(row.value_json)
if isinstance(val, str) and val.strip():
return date.fromisoformat(val.strip())
return None
def effective_today(db=None) -> date:
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata)."""
try:
if db is not None:
demo_date = _read_demo_date_from_db(db)
if demo_date is not None:
return demo_date
else:
from .db import SessionLocal
with SessionLocal() as session:
demo_date = _read_demo_date_from_db(session)
if demo_date is not None:
return demo_date
except Exception:
pass
return datetime.now(KOLKATA).date()
def effective_now_utc(db=None) -> datetime:
"""Returns current UTC datetime anchored to effective_today(db) in Asia/Kolkata when demo date is set."""
now_kol = datetime.now(KOLKATA)
today = effective_today(db)
if today == now_kol.date():
return now_kol.astimezone(timezone.utc)
return KOLKATA.localize(datetime.combine(today, now_kol.timetz().replace(tzinfo=None))).astimezone(
timezone.utc
)
def to_kolkata(dt: datetime) -> datetime:
return dt.astimezone(KOLKATA)
def format_datetime(dt: datetime | None) -> str | None:
if dt is None:
return None
local = to_kolkata(dt) if dt.tzinfo else KOLKATA.localize(dt)
return local.strftime("%d-%b-%Y %H:%M")
def format_date(d: date | None) -> str | None:
if d is None:
return None
return d.strftime("%d-%b-%Y")
def add_months(d: date, months: int) -> date:
"""Add calendar months to a date, clamping day-of-month to the target month's length."""
total_months = (d.year * 12 + (d.month - 1)) + months
year, zero_month = divmod(total_months, 12)
month = zero_month + 1
max_day = calendar.monthrange(year, month)[1]
return date(year, month, min(d.day, max_day))
def format_duration(minutes: int | None) -> str:
if minutes is None:
return "\u2014"
minutes = int(minutes)
d, rem = divmod(minutes, 1440)
h, m = divmod(rem, 60)
parts = []
if d:
parts.append(f"{d}d")
if h:
parts.append(f"{h}h")
if m or not parts:
parts.append(f"{m}m")
return " ".join(parts)