Converting a column of minutes to hours and minutes python
12,906
Solution 1
Assuming your DataFrame looks like this:
df = pd.DataFrame({'duration': [20, 10, 80, 120, 30, 190]})
Using pd.to_datetime
with strftime
:
pd.to_datetime(df.duration, unit='m').dt.strftime('%H:%M')
0 00:20
1 00:10
2 01:20
3 02:00
4 00:30
5 03:10
dtype: object
Solution 2
I’m not familiar with Pandas, but a general way to do the conversion from minutes to minutes and hours is shown below:
total_minutes = 374
# Get hours with floor division
hours = total_minutes // 60
# Get additional minutes with modulus
minutes = total_minutes % 60
# Create time as a string
time_string = "{}:{}".format(hours, minutes)
print(time_string) # Prints '6:14' in this example
You can also avoid the intermediate steps using divmod()
:
time_string = "{}:{}".format(*divmod(total_minutes, 60))
Here, the *
allows for format()
to accept the tuple (containing two integers) returned by divmod()
as two separate arguments.
Solution 3
If the duration is larger than 24:00 hours, you can use:
df.duration = df.duration.apply(lambda x: '{:02d}:{:02d}'.format(*divmod(x, 60)))
For instance given a df:
df = pd.DataFrame({'duration': [20, 10, 80, 120, 30, 190]})
After applying the operator we get:
- 00:20
- 00:10
- 01:20
- 02:00
- 00:30
- 03:10
- 40:40
Author by
Sharkfan1781110
Updated on June 14, 2022Comments
-
Sharkfan1781110 almost 2 years
I have a Dataframe in Pandas with a column called "duration" given in minutes.
I want to get a new column that gives the duration in Hours:Minutes (HH:MM).