fix: present web timestamps in UTC+3

This commit is contained in:
nyan404 committed 2026-09-01 01:51:29 +03:00
1 parent 00bbe66c77
commit cffaaac755
8 files changed
+25 -18

No files matched your search

+6 -4
View File
@@ -11,10 +11,11 @@ PERIODS = {
"6h": timedelta(hours=6), "4h": timedelta(hours=4), "2h": timedelta(hours=2),
"1h": timedelta(hours=1),
}
WEB_TIMEZONE = timezone(timedelta(hours=3), name="UTC+3")
def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime:
"""Parse an ISO date/time stored by either SQLite or PostgreSQL as UTC."""
def parse_timestamp(value: str, *, end_of_day: bool = False, web_input: bool = False) -> datetime:
"""Parse a stored UTC instant or a date entered in the UTC+3 web interface."""
text = value.strip().replace("Z", "+00:00")
if len(text) == 10:
text += "T23:59:59.999999" if end_of_day else "T00:00:00"
@@ -22,7 +23,8 @@ def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime:
result = datetime.fromisoformat(text)
except ValueError as exc:
raise ValueError("Дата должна быть в формате ГГГГ-ММ-ДД") from exc
return result.replace(tzinfo=result.tzinfo or timezone.utc).astimezone(timezone.utc)
assumed_timezone = WEB_TIMEZONE if web_input else timezone.utc
return result.replace(tzinfo=result.tzinfo or assumed_timezone).astimezone(timezone.utc)
def period_bounds(period: str, date_from: str | None, date_to: str | None, *, now: datetime | None = None) -> tuple[datetime | None, datetime | None]:
@@ -30,7 +32,7 @@ def period_bounds(period: str, date_from: str | None, date_to: str | None, *, no
if date_from or date_to:
if not date_from or not date_to:
raise ValueError("Укажите обе даты диапазона")
start, end = parse_timestamp(date_from), parse_timestamp(date_to, end_of_day=True)
start, end = parse_timestamp(date_from, web_input=True), parse_timestamp(date_to, end_of_day=True, web_input=True)
if start > end:
raise ValueError("Дата начала не может быть позже даты окончания")
return start, end
+7 -7
View File
@@ -7,7 +7,7 @@ from xml.sax.saxutils import escape
from zipfile import ZIP_DEFLATED, ZipFile
def _cell(column: int, row: int, value: object, *, header: bool = False) -> str:
def _cell(column: int, row: int, value: object, *, header: bool = False, display_timezone: timezone = timezone.utc) -> str:
name = ""
number = column
while number:
@@ -16,22 +16,22 @@ def _cell(column: int, row: int, value: object, *, header: bool = False) -> str:
reference = f"{name}{row}"
style = ' s="1"' if header else ''
if isinstance(value, datetime):
timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(timezone.utc)
serial = (timestamp - datetime(1899, 12, 30, tzinfo=timezone.utc)).total_seconds() / 86400
timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(display_timezone)
serial = (timestamp.replace(tzinfo=None) - datetime(1899, 12, 30)).total_seconds() / 86400
return f'<c r="{reference}" s="2"><v>{serial:.10f}</v></c>'
if isinstance(value, (int, float)) and not isinstance(value, bool):
return f'<c r="{reference}"{style}><v>{value}</v></c>'
return f'<c r="{reference}" t="inlineStr"{style}><is><t>{escape(str(value or ""))}</t></is></c>'
def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
"""Builds one readable XLSX worksheet with a frozen, styled header row."""
def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]], display_timezone: timezone = timezone.utc) -> bytes:
"""Build a workbook with dates converted to its user-facing time zone."""
sheet_rows = [
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True) for index, value in enumerate(headers, 1)) + '</row>'
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True, display_timezone=display_timezone) for index, value in enumerate(headers, 1)) + '</row>'
]
for row_number, row in enumerate(rows, 2):
sheet_rows.append('<row r="%d">%s</row>' % (row_number, ''.join(
_cell(index, value_row, value) for index, value in enumerate(row, 1) for value_row in (row_number,)
_cell(index, value_row, value, display_timezone=display_timezone) for index, value in enumerate(row, 1) for value_row in (row_number,)
)))
widths = ''.join(f'<col min="{index}" max="{index}" width="{min(max(max([len(header)] + [len(str(row[index - 1] or "")) for row in rows]) + 2, 14), 48)}" customWidth="1"/>' for index, header in enumerate(headers, 1))
sheet = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'