Search code examples
pythonpandasdatetimedate-formattingdate-conversion

How to convert daytime to day in python?


I have the following table :

DayTime
1 days 19:55:00
134 days 15:34:00

How to convert the Daytime to fully day? Which mean the hours will change to day(devide by 24)


Solution

  • You can convert Timedeltas to numerical units of time by dividing by units of Timedelta. For instance,

    import pandas as pd
    df = pd.DataFrame({'DayTime':['1 days 19:55:00', '134 days 15:34:00']})
    df['DayTime'] = pd.to_timedelta(df['DayTime'])
    days = df['DayTime'] / pd.Timedelta(hours=24) 
    print(days)
    

    yields

    0      1.829861
    1    134.648611
    Name: DayTime, dtype: float64
    

    Note that above I'm assuming that 1 day = 24 hours. That's not always exactly true. Some days are 24 hours + 1 leap second long.