Source code for ds_common_placeholder_py_lib.functions.time

"""
**File:** ``functions/time.py``
**Region:** ``ds-common-placeholder-py-lib``

Description
-----------
Time functions depend only on their arguments, never on the context: the
date functions compute from the time they are given, their last argument
(``@{get_hour, UTC, '2026-05-03T01:30:00Z'}``, or any reference the
caller's context holds), or from the current time when none is (contract
ยง5). Outputs match the ``legacy``
builtins at the same instant, except ``get_current_date``, which returns an
ISO string.
"""

from __future__ import annotations

import calendar
import re
from contextvars import ContextVar
from datetime import UTC, date, datetime, timedelta
from functools import cache
from typing import Any
from zoneinfo import ZoneInfo, available_timezones

from ..errors import ErrorCode, PlaceholderError

_MONTHS = {
    "EN": (
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December",
    ),
    "NO": (
        "Januar", "Februar", "Mars", "April", "Mai", "Juni",
        "Juli", "August", "September", "Oktober", "November", "Desember",
    ),
}  # fmt: skip

# RFC 3339, the form the router writes. Stricter than datetime.fromisoformat.
_TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})")


@cache
def _timezones() -> frozenset[str]:
    return frozenset(available_timezones())


[docs] def check_timezone(name: str) -> ZoneInfo: """Return the zone for an IANA name. Raises: PlaceholderError: ``argument`` if the name is not an IANA zone. """ if name not in _timezones(): raise PlaceholderError(ErrorCode.ARGUMENT, "unknown timezone" + _time_goes_last(name)) return ZoneInfo(name)
def _time_goes_last(value: str) -> str: """A hint when a time was given where an earlier argument goes.""" return " (a time goes after the timezone, as the last argument)" if _TIMESTAMP.fullmatch(value) else ""
[docs] def check_language(name: str) -> str: """Return *name* if it is ``EN`` or ``NO``. Raises: PlaceholderError: ``argument`` otherwise. """ if name not in _MONTHS: raise PlaceholderError(ErrorCode.ARGUMENT, "language must be 'EN' or 'NO'" + _time_goes_last(name)) return name
class _NotGiven: """The ``at`` argument left out: the current time.""" def __repr__(self) -> str: return "NOT_GIVEN" NOT_GIVEN: Any = _NotGiven() """The default of ``at``: kept apart from any string, so ``''`` is an error, never the current time."""
[docs] def check_at(value: str) -> datetime: """The time *value* names, an RFC 3339 timestamp. Raises: PlaceholderError: ``argument`` if *value* is not an RFC 3339 timestamp with ``Z`` or an offset (``''`` included). """ if not _TIMESTAMP.fullmatch(value): raise PlaceholderError(ErrorCode.ARGUMENT, "the time must be an RFC 3339 timestamp") try: return datetime.fromisoformat(value) except ValueError: raise PlaceholderError(ErrorCode.ARGUMENT, "the time must be an RFC 3339 timestamp") from None
# A fixed "now" while ds_common_placeholder_py_lib.testing.fixed_now is active, # in that thread or async task only. _FIXED_NOW: ContextVar[datetime | None] = ContextVar("fixed_now", default=None) def _now(timezone: str, at: Any = NOT_GIVEN) -> datetime: """The time the function computes from, in *timezone*: *at* when given, else the current time.""" zone = check_timezone(timezone) given = (_FIXED_NOW.get() or datetime.now(UTC)) if at is NOT_GIVEN else check_at(at) return given.astimezone(zone) def _previous_month(now: datetime) -> tuple[int, int]: return (now.year, now.month - 1) if now.month > 1 else (now.year - 1, 12)
[docs] def get_start_last_month(args: list[Any]) -> str: """First instant of last month, e.g. ``2026-04-01T00:00:00+00:00``.""" now = _now(args[0], args[1]) year, month = _previous_month(now) return datetime(year, month, 1, tzinfo=now.tzinfo).isoformat()
[docs] def get_end_last_month(args: list[Any]) -> str: """Last microsecond of last month, e.g. ``2026-04-30T23:59:59.999999+00:00``.""" now = _now(args[0], args[1]) year, month = _previous_month(now) last = calendar.monthrange(year, month)[1] return datetime(year, month, last, 23, 59, 59, 999999, tzinfo=now.tzinfo).isoformat()
[docs] def get_start_date_last_month(args: list[Any]) -> str: """First day of last month, e.g. ``2026-04-01``.""" year, month = _previous_month(_now(args[0], args[1])) return date(year, month, 1).isoformat()
[docs] def get_end_date_last_month(args: list[Any]) -> str: """Last day of last month, e.g. ``2026-04-30``.""" year, month = _previous_month(_now(args[0], args[1])) return date(year, month, calendar.monthrange(year, month)[1]).isoformat()
[docs] def get_last_month_period(args: list[Any]) -> str: """Last month as ``<Month> <year>``, e.g. ``April 2026``.""" language = check_language(args[0]) year, month = _previous_month(_now(args[1], args[2])) return f"{_MONTHS[language][month - 1]} {year}"
[docs] def get_current_date(args: list[Any]) -> str: """The date, e.g. ``2026-05-03``.""" return _now(args[0], args[1]).date().isoformat()
[docs] def get_day_of_month(args: list[Any]) -> int: """The day of month.""" return _now(args[0], args[1]).day
[docs] def get_previous_day_of_month(args: list[Any]) -> int: """The day of month one day before.""" return (_now(args[0], args[1]).date() - timedelta(days=1)).day
[docs] def get_hour(args: list[Any]) -> int: """The hour, 0-23.""" return _now(args[0], args[1]).hour
[docs] def get_previous_hour(args: list[Any]) -> int: """The local hour one elapsed hour before, 0-23. Across a DST change this differs from ``legacy``, which subtracted wall time.""" now = _now(args[0], args[1]) return (now.astimezone(UTC) - timedelta(hours=1)).astimezone(now.tzinfo).hour
[docs] def get_iso_timestamp_now(args: list[Any]) -> str: """The current time to the second, e.g. ``2026-05-03T03:30:00+02:00``.""" return _now(args[0]).isoformat("T", "seconds")
[docs] def get_unix_timestamp_now(args: list[Any]) -> int: """The current UNIX timestamp in whole seconds.""" return int(_now(args[0]).timestamp())