Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a column of minutes to hours and minutes python

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 ).

like image 926
Sharkfan1781110 Avatar asked Jul 27 '18 21:07

Sharkfan1781110


2 Answers

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
like image 174
user3483203 Avatar answered Sep 19 '22 22:09

user3483203


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.

like image 35
Chris Avatar answered Sep 20 '22 22:09

Chris