pythondatetimepython-polars

cast datetime[ms] to datetime[ns] in polars


I'd like to cast a column with the type datetype[ms] to datetime[ns] in polars. Is there a easy way to do this?

I think there's a problem with group_by_dynamic when using datetime[ms] and I'd like to test this


Solution

  • You can use .dt.cast_time_unit()

    s = pl.datetime_range(
            pl.datetime(2021, 1, 1), pl.datetime(2021, 1, 2),
            interval="3h", time_unit="ns", eager=True
    )
    
    s.dt.cast_time_unit("ms")
    
    shape: (9,)
    Series: '' [datetime[ms]]
    [
        2021-01-01 00:00:00
        2021-01-01 03:00:00
        2021-01-01 06:00:00
        2021-01-01 09:00:00
        2021-01-01 12:00:00
        2021-01-01 15:00:00
        2021-01-01 18:00:00
        2021-01-01 21:00:00
        2021-01-02 00:00:00
    ]