[Python] How to add a timezone to a datetime object?

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have a variable which is grabbing a date object from a file. My aim is to add a timezone to this object so that it automatically changes the time based on the date its it then. So I expected it to add +1hour to it for dates in summertime (between march and october) and add +0hour in wintertime (between october and march).

    dt_object = '20200901-01u30m30s'
    dt_object = datetime.datetime.strptime(dt_object, '%Y%m%d-%Hu%Mm%Ss')

    >>>print(dt_object) >>> 2020-09-01 01:30:30

    timezone= 'Europe/Amsterdam'
    dt_object_tz = pytz.utc.localize(dt_object).astimezone(pytz.timezone(timezone))
    timeDiff = dt_object_tz.utcoffset().total_seconds()
    official_time = pytz.utc.localize(dt_object_tz+datetime.timedelta(seconds=timeDiff))

    >>>print(official_time) >>> 2020-09-01 03:30:30+00:00


    As you can see this is a datetime object of september (so summertime!), I literally have no clue why it adds +2hours instead of 1 hour.... Can someone explain it and tell me what went wrong?

    I just want my datetime object to be timezone-aware so it autmatically changes from summer to wintertime based on the date in grabs.

    Continue reading...

Compartilhe esta Página