[Python] Calculate hours in period. DST aware

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I want to calculate a DST aware figure for the total hours in a period localized for Europe/London.

    Given the start time, I need to generate the end time and then calculate the hours in period.

    For example:
    MONTHLY PERIOD

    # define start
    s = pd.to_datetime('2023-03-01').tz.localize('Europe/London')

    >>> Timestamp('2023-03-01 00:00:00+0000', tz='Europe/London')

    # generate end
    e = (s + pd.offsets.MonthEnd()) + pd.Timedelta(days=1)

    >>> Timestamp('2023-04-01 01:00:00+0100', tz='Europe/London')

    # calculate hrs in period
    (e - s) / pd.Timedelta(hours = 1)

    >>> 743.0


    This seems accurate and provides the correct result as, in the UK, an hour is lost in March.
    However, when changing the year to 2024 and setting s = pd.to_datetime('2024-03-01').tz.localize('Europe/London'), an incorrect result of 744 is returned.

    I'd like a full proof way of calculating hours in period please.

    Continue reading...

Compartilhe esta Página