'Calculating number of hours in Excel with Python
I have a Dataframe with a column listing the duration of some events in minutes. I would like to calculate in a new column what the duration is in hours. The format of the data would be a date - time one. The durations can be up to 3000+ minutes, resulting in a number of hours that would be well above 24:00:00. Currently my formula is this one:
df['Durée contractuelle (h)'] = df.apply(lambda x: x['Durée contractuelle (mn)']/(60*24) ,axis=1)
However, I'm getting float results in my new column like 1.638, 1.892, etc. How do I transform it, in order to obtain the right format? The expected result for;
2,355 minutes is 39:15:00 (hours), and not 1,638.
Solution 1:[1]
try this
def myfunc(x):
# test value -> x = 2355
h = x/60
m = int(60*(int(str(h).split(".")[1])/100))
h = int(str(h).split(".")[0])
s = int(60*(int(str(m/60).split(".")[0])/100))
m = int(m)
h = int(h)
s = int(s)
print(f'{h}:{m}:{s}')
return f'{h}:{m}:{s}'
df['Durée contractuelle (h)'] = df.apply(lambda x: myfunc(x) ,axis=1)
```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
