[Python] Adding hours to a polars time column in python

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a table representing a schedule, i.e. it contains day (monday-sunday), start_time and end_time fields

    df = pl.DataFrame({
    "day": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"],
    "enabled": [True, True, True, True, True, False, False],
    "start_time": ["09:00", "09:00", "09:00", "09:00", "09:00", "00:00", "00:00"],
    "end_time": ["18:00", "18:00", "18:00", "18:00", "18:00", "00:00", "00:00"],
    })

    df = df.with_columns(start_time = pl.col("start_time").str.to_time("%H:%M"))
    df = df.with_columns(end_time = pl.col("end_time").str.to_time("%H:%M"))

    print(df)


    shape: (7, 4)
    ┌───────────┬─────────┬────────────┬──────────┐
    │ day ┆ enabled ┆ start_time ┆ end_time │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ bool ┆ time ┆ time │
    ╞═══════════╪═════════╪════════════╪══════════╡
    │ monday ┆ true ┆ 09:00:00 ┆ 18:00:00 │
    │ tuesday ┆ true ┆ 09:00:00 ┆ 18:00:00 │
    │ wednesday ┆ true ┆ 09:00:00 ┆ 18:00:00 │
    │ thursday ┆ true ┆ 09:00:00 ┆ 18:00:00 │
    │ friday ┆ true ┆ 09:00:00 ┆ 18:00:00 │
    │ saturday ┆ false ┆ 00:00:00 ┆ 00:00:00 │
    │ sunday ┆ false ┆ 00:00:00 ┆ 00:00:00 │
    └───────────┴─────────┴────────────┴──────────┘


    I need to subtract n hours from the start_time and add n hours to the end_time. I cannot find a polars operation to add/subtract hours from a pl.time - I've tried adding a pl.duration but that only appears to work for date and datetime.

    One work-around I've assumed is to turn start_time / end_time into a pl.datetime (i.e. use some constant date), do the operation and then decompose the result back to a time. This has one option of being easier to ensure I don't over/underflow (i.e. subtract 2 hours from 01:00 and end up with 23:00) but I'm wondering it's possible to add/subtracts hours/minutes to a time in polars?

    Continue reading...

Compartilhe esta Página