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
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With