[Solved] Hours and time converting to a certain format [closed]


This can be done conveniently by using the appropriate representation for your fractional hours, namely a timedelta. If the input is of datatype string, convert to float first.

Ex:

from datetime import datetime, timedelta

for td in [8.25, 17.75]:
    # add the duration as timedelta to an arbitrary date to get a time object:
    print((datetime(2020,1,1) + timedelta(hours=td)).time())
08:15:00
17:45:00

Using pandas, that could look like

import pandas as pd

s = pd.Series([8.25, 17.75])

refDate="2020-01-01" # need a date..

t = pd.Timestamp(refDate) + pd.to_timedelta(s, unit="h")

print(t)

# 0   2020-01-01 08:15:00
# 1   2020-01-01 17:45:00
# dtype: datetime64[ns]

print(t.dt.time)

# 0    08:15:00
# 1    17:45:00
# dtype: object

solved Hours and time converting to a certain format [closed]