0

Given a Python 3.9 datetime set with UTC time zone, I am trying to use astimezone with datetime.timezone to create a new datetime by applying a timedelta offset value obtained at runtime. I am struggling to understand the representation of the tzinfo in the resultant datetime.

A small replicable example for what I am struggling to understand, is included in the listing below. Actual runtime results are highlighted in the comments.

In this example, I am trying to apply a timezone offset that is 1 hour (3600 seconds) earlier than the UTC time.

import datetime

if __name__ == "__main__":
    offset = 3600
    day = datetime.datetime(2021, 8, 22, 23, 59, 31, tzinfo=datetime.timezone.utc)
    hour_before = day.astimezone(datetime.timezone(-datetime.timedelta(seconds=offset)))

    print(f"day={day.isoformat()}")
    print(f"hour before={hour_before.isoformat()}")

    """

    day=2021-08-22T23:59:31+00:00
    hour before=2021-08-22T22:59:31-01:00

    >>> dt = datetime(2021, 8, 22, 23, 59, 31, tzinfo=timezone.utc)
    >>> hour_before=dt.astimezone(timezone(-timedelta(seconds=3600)))
    >>> hour_before
    datetime.datetime(2021, 8, 22, 22, 59, 31, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=82800)))
    >>> 
    """

Running this code gives the expected results when printing the date as an ISO-8601 date string.

However when I inspect the value of the tzinfo in the resultant datetime instance in a python interactive interpreter, it gives:

    >>> dt = datetime(2021, 8, 22, 23, 59, 31, tzinfo=timezone.utc)
    >>> hour_before=dt.astimezone(timezone(-timedelta(seconds=3600)))
    >>> hour_before
    datetime.datetime(2021, 8, 22, 22, 59, 31, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=82800)))

I cannot understand why the resultant datetime.timedelta is days=-1, seconds=82800.

Why is it not an hour earlier as seconds=-3600? Why is days = -1 when the resultant date is the same, year, day, month??

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
anon_dcs3spp
  • 1,490
  • 1
  • 15
  • 40

0 Answers0