Search code examples
pandasdataframedatetimehour

Extraction of hour from datetime object in Pandas


When I extract hours from 23.35 using dt.hour in pandas it returns 0. But i want to get 24. How to do that?


Solution

  • Assuming this input:

    s = pd.to_datetime(pd.Series(['00:10', '12:30', '23:35']))
    0   2022-04-18 00:10:00
    1   2022-04-18 12:30:00
    2   2022-04-18 23:35:00
    dtype: datetime64[ns]
    

    hours

    s.dt.hour
    0     0
    1    12
    2    23
    dtype: int64
    

    An indeed, if you round:

    s.dt.round('h').dt.hour
    0     0
    1    12
    2     0
    dtype: int64
    

    what you can do it to convert rounded hour+minutes

    s.dt.hour.add(s.dt.minute/60).round().astype(int)
    0     0
    1    12
    2    24
    dtype: int64