pythondatetimetimedeltadsttzinfo

Python datetime DST when tzinfo is None


Calling the method timestamp at the last Sunday of march returns:

>>> from datetime import datetime
>>> before = datetime.fromisoformat("2023-03-26 02:00:01")
>>> after = datetime.fromisoformat("2023-03-26 03:00:01")
>>> print(before.tzinfo)
None
>>> print(after.tzinfo)
None
>>> after.timestamp() - before.timestamp()
0.0

They are equal even they are separated by an hour. I was expecting that daylight saving time was not handled when tzinfo is None

Meanwhile, when using the subtract operator, it catches the difference

>>> after - before
datetime.timedelta(seconds=3600)

Solution

  • https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp

    Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion.

    "naive" means without tzinfo, so the timestamp method implicitly treats them as local time, hence the zero difference you see.

    Meanwhile the after - before date math treats them as abstract datetimes with no timezone, so the resulting timedelta does not take DST into account.