[Python] Pandas Timedelta UnitChoices typing

Discussão em 'Python' iniciado por Stack, Maio 18, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing some python code using typehints and using mypy to check them. I have a variable period that I stated was a string. I later use that variable to instantiate a pandas.Timedelta object, setting the units to period. Here is a minimally reproducible example:

    import pandas as pd

    period: str = "minute"
    my_timedelta = pd.Timedelta( 30, unit=period)

    print(my_timedelta)


    The above code runs fine and creates a Timedelta object of 30 minutes:

    $ python example.py
    0 days 00:30:00
    $


    When I run mypy on the above code, I get the following error:

    (pdmkt) dino@DINO(24):~/code/pdmkt$ mypy example.py
    example.py:5: error: Argument "unit" to "Timedelta" has incompatible type "str"; expected "Literal['W', 'w', 'D', 'd', 'days', 'day', 'hours', 'hour', 'hr', 'h', 'm', 'minute', 'min', 'minutes', 's', 'seconds', 'sec', 'second', 'ms', 'milliseconds', 'millisecond', 'milli', 'millis', 'us', 'microseconds', 'microsecond', 'µs', 'micro', 'micros', 'ns', 'nanoseconds', 'nano', 'nanos', 'nanosecond']" [arg-type]
    Found 1 error in 1 file (checked 1 source file)


    Obviously I could declare a type using the Literal, and modify my code so that period is that type:

    import pandas as pd
    import typing

    PERIOD_TYPE = typing.Literal['W', 'w', 'D', 'd', 'days', 'day', 'hours', 'hour', 'hr', 'h', 'm', 'minute', 'min', 'minutes', 's', 'seconds', 'sec', 'second', 'ms', 'milliseconds', 'millisecond', 'milli', 'millis', 'us', 'microseconds', 'microsecond', 'µs', 'micro', 'micros', 'ns', 'nanoseconds', 'nano', 'nanos', 'nanosecond']

    period: PERIOD_TYPE = "minute"
    my_timedelta = pd.Timedelta( 30, unit=period)

    print(my_timedelta)


    The above code works the same as the first, and mypy reports: "Success: no issues found in 1 source file"

    However, rather than declare my own type, it makes sense to me to somehow import the type from Pandas. I looked through the pandas code and found this file: https://github.com/pandas-dev/pandas/blob/main/pandas/core/tools/timedeltas.py which contains the line:

    from pandas._libs.tslibs.timedeltas import UnitChoices


    In timedeltas.py the variable unit is of type UnitChoices, so obviously UnitChoices is the type that I want to use.

    HERE'S MY QUESTION:

    How can I import and use UnitChoices from Pandas?

    Continue reading...

Compartilhe esta Página