aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/template_filters.py
blob: e6cac2d3a05dd5d438d2cdc1bd58650415799437 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Helpers for displaying UTC timestamps in templates."""

from datetime import UTC, datetime

import humanize


def as_utc(value: datetime) -> datetime:
    """Normalize a timestamp to UTC, treating timezone-naive DB values as UTC."""
    if value.tzinfo is None:
        return value.replace(tzinfo=UTC)
    return value.astimezone(UTC)


def utc_isoformat(value: datetime) -> str:
    """Return an unambiguous machine-readable timestamp for the time element."""
    return as_utc(value).isoformat()


def utc_timestamp(value: datetime) -> str:
    """Return the complete UTC timestamp for the hover tooltip."""
    return as_utc(value).strftime("%Y-%m-%d %H:%M:%S UTC")


def relative_time(value: datetime) -> str:
    """Render a timestamp as a human-readable age relative to the current UTC time."""
    return humanize.naturaltime(datetime.now(UTC) - as_utc(value))