2024-01-25 Formatage de dates aware à la milliseconde près en Python/Django

from zoneinfo import ZoneInfo
from django.conf import settings
from django.db import models
from django.utils.translation import gettext as _
from datetime import datetime
import pytz
from django.conf import settings

# dans une fonction
now = datetime.now(pytz.timezone("Europe/Paris"))
now_str = now.strftime("%Y-%m-%d %H:%M:%S.%f")

# dans une classe

class StatsParameters(models.Model):
    """The parameters table for the stats tables"""

    class Meta:
        managed = True
        db_table = "stats_parameters"
        verbose_name = _("stats_parameters")
        verbose_name_plural = _("stats parameters")

    last_update_time = models.DateTimeField(
        null=True,
        help_text=_("Last update datetime"),
    )

    def get_last_update_time_str(self) -> str:
        last_update = self.last_update_time
        last_update = last_update.astimezone(ZoneInfo(settings.TIME_ZONE))
        last_update_time_str = last_update.strftime("%Y-%m-%d %H:%M:%S.%f")
        return last_update_time_str