Skip to content Skip to sidebar Skip to footer

Hours And Time Converting To A Certain Format

I have been trying to change the following format of time 8.25 (fractional hours) to 8.15 meaning 8:15. And 17.75 to 17.45 meaning 17:45. The problem is that I specifically need th

Solution 1:

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

Solution 2:

Given your string of format HH.MM, you can approach it as follows:

my_time = "17.75"
hours, minutes = my_time.split(".")  # (17, 75)
minutes_converted = round(float(minutes) / 100 * 60)  # 45
my_time_converted = "{}.{}".format(hours, minutes_converted)  #17.45print(my_time_converted)

> 17.45

Post a Comment for "Hours And Time Converting To A Certain Format"