47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import pandas as pd
|
|
|
|
US_TIMEZONE_OPTIONS: list[str] = [
|
|
"America/New_York",
|
|
"America/Chicago",
|
|
"America/Denver",
|
|
"America/Los_Angeles",
|
|
"America/Phoenix",
|
|
"America/Anchorage",
|
|
"Pacific/Honolulu",
|
|
]
|
|
|
|
DEFAULT_DISPLAY_TIMEZONE = "America/Chicago"
|
|
|
|
|
|
def normalize_display_timezone(value: Any, fallback: str = DEFAULT_DISPLAY_TIMEZONE) -> str:
|
|
candidate = str(value or "").strip()
|
|
if candidate in US_TIMEZONE_OPTIONS:
|
|
return candidate
|
|
return fallback if fallback in US_TIMEZONE_OPTIONS else DEFAULT_DISPLAY_TIMEZONE
|
|
|
|
|
|
def format_timestamp(
|
|
value: Any,
|
|
display_timezone: str = DEFAULT_DISPLAY_TIMEZONE,
|
|
use_24h_time: bool = False,
|
|
) -> str:
|
|
try:
|
|
ts = pd.Timestamp(value)
|
|
except Exception:
|
|
return "n/a"
|
|
|
|
tz_name = normalize_display_timezone(display_timezone)
|
|
try:
|
|
if ts.tzinfo is None:
|
|
ts = ts.tz_localize("UTC")
|
|
converted = ts.tz_convert(tz_name)
|
|
if use_24h_time:
|
|
return converted.strftime("%Y-%m-%d %H:%M %Z")
|
|
return converted.strftime("%Y-%m-%d %I:%M %p %Z").replace(" 0", " ", 1)
|
|
except Exception:
|
|
return "n/a"
|