代码之家  ›  专栏  ›  技术社区  ›  bzm3r

如何键入提示“pl.date”?

  •  0
  • bzm3r  · 技术社区  · 2 年前

    假设我们创建一些日期:

    import polars as pl
    
    df = pl.DataFrame(
        [
            pl.Series("start", ["2023-01-01"], dtype=pl.Date).str.to_date(),
            pl.Series("end", ["2024-01-01"], dtype=pl.Date).str.to_date(),
        ]
    )
    

    现在我可以根据以下内容创建日期范围:

    dates = pl.date_range(df[0, "start"], df[0, "end"], "1mo", eager=True)
    

    但我想定义一个函数,它接受几个日期并输出一个范围,作为包装 pl.date_range :

    def my_date_range(start: pl.Date, end: pl.Date) -> pl.Series:
        return pl.date_range(start, end, "1mo", eager=True)
    

    以上内容与不匹配 pyright /Pylance,因为:

    Argument of type "Date" cannot be assigned to parameter "start" of type "IntoExprColumn | date | datetime" in function "date_range"
      Type "Date" is incompatible with type "IntoExprColumn | date | datetime"
        "Date" is incompatible with "date"
        "Date" is incompatible with "datetime"
        "Date" is incompatible with "Expr"
        "Date" is incompatible with "Series"
        "Date" is incompatible with "str"PylancereportArgumentType
    

    如果我退房 type(df[0, "start"]) ,我明白了:

    datetime.date
    

    pl.Date 不好,因为 isinstance(df[0, "start"], pl.Date) == False .

    我不知道如何导入 datetime.date 以便将其用作类型注释(尝试 import polars.datetime as dt 加薪 No module named 'polars.datetime' ).

    如何做到这一点?或者换一种说法:应该如何 my_date_range 的日期参数是否被注释?

    1 回复  |  直到 2 年前
        1
  •  3
  •   Marcin Orlowski    2 年前

    自从 datetime.date 与兼容 start end 预期的参数 pl.date_range() 这应该是足够的:

    import polars as pl
    from datetime import date
    
    def my_date_range(start: date, end: date) -> pl.Series:
        return pl.date_range(start, end, "1mo", eager=True)
    
    推荐文章