79189802

Date: 2024-11-14 17:18:30
Score: 1
Natty:
Report link

These are 3 alternative ways to avoid DST handling:

  1. Use an aware datetime (with tzinfo=UTC) instead of naive:

    >>> before_utc = before.replace(tzinfo=timezone.utc)
    >>> after_utc = after.replace(tzinfo=timezone.utc)
    >>> after_utc.timestamp() - before_utc.timestamp()
    3600.0
    >>> after_utc - before_utc
    datetime.timedelta(seconds=3600)
    

The following 2 alternatives continue using naive datetime, as in the OP. In the context of the datetime.timestamp() method naive means local time and is delegated to the platform function mktime() (as shown in the @anentropic answer).

  1. Set the environment variable TZ=Etc/Utc

  2. Debian specific. Change the content of /etc/timezone. In my system it contains Europe/Madrid. An interactive way to change it is through the dpkg-reconfigure tzdata command

If several of those methods are used at the same time, the order of preference is the same in which they are listed.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @anentropic
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Isidro Arias