William
William

Reputation: 4030

How to convert a float date to days and hours

I have a Dataframe ,you can have it ,by runnnig:

import pandas as pd
from io import StringIO

df = """
case_id         duration_time  other_column
   3456         1              random value 1
   7891         3              ddd
   1245         0              fdf
   9073         null           111
 """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

Now I first drop the null rows by using dropna function, then calculate the average value of the left duration_time as average_duration:

average_duration=df.duration_time.duration_time.dropna.mean() 

The output is average_duration:

1.3333333333333333

My question is how can I convert the result to something similar as:

average_duration = '1 day,8 hours'

Since 1.33 days is 1 day and 7.92 hours

Upvotes: 0

Views: 163

Answers (2)

Selcuk
Selcuk

Reputation: 59184

There are third party libraries that might do a better job, but it is trivial to define your own function:

def time_passed(duration: float):
    days = int(duration)
    hours = round((duration - days) * 24)
    return f"{days} days, {hours} hours"


print(time_passed(1.3333333333333333))

This should print

1 days, 8 hours

Upvotes: 2

Timeless
Timeless

Reputation: 37747

With , you can use timedelta :

td = pd.Timedelta(days=average_duration)
​
d, h = td.components.days, td.components.hours

Output :

print("average_duration:", f"{d} day(s), {h} hour(s)")
​
average_duration: 1 day(s), 8 hour(s)

If you need to define the result/string a variable, use this :

average_duration = f"{d} day(s), {h} hour(s)"

Upvotes: 4

Related Questions