[Python] Why can Pandas weekday DateOffset only move the date forward?

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to find the last of a weekday in a month. For example, let us say the last Sunday in October.

    I try to do like this:

    pd.Timestamp("2025-10-31") - pd.DateOffset(weekday=6)


    The resulting date is Timestamp('2025-11-02 00:00:00'), i.e. the result is a later date despite the minus. The result is also identical if I add in stead of subtract.

    This is in contrast to:

    >>> pd.Timestamp("2025-10-31") - pd.DateOffset(days=2)
    Timestamp('2025-10-29 00:00:00')

    >>> pd.Timestamp("2025-10-31") - pd.DateOffset(day=2)
    Timestamp('2025-10-02 00:00:00')


    which result in an earlier date as I expect, so the behaviour is just different for 'weekday' than for other offsets.

    If I attempt to use the DateOffset.rollback method instead, it simply does not change the date:

    >>> pd.DateOffset(weekday=6).rollback(pd.Timestamp("2025-10-31"))
    Timestamp('2025-10-31 00:00:00')


    I cannot find anything in the DateOffset or DateOffset.rollback documentation that describes this.

    What can I do to make this work?

    Continue reading...

Compartilhe esta Página