Converting a column of minutes to hours and minutes python
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
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.