Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting minutes to HH:MM format in Python [duplicate]

Tags:

python

time

First of all, I'd like to point out that I'm a beginner with Python.

My problem is that I can't figure out what is the proper way to convert minutes to HH:MM format in Python.

Any help is appreciated!

like image 520
mllnd Avatar asked Nov 29 '13 18:11

mllnd


People also ask

How do you convert time to hours and minutes in Python?

Using Datetime module You can also use the timedelta method under the DateTime module to convert seconds into the preferred format. It displays the time as days, hours, minutes, and seconds elapsed since the epoch.

How do I print HH mm format in Python?

Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format. For example, datetime.

How do you convert minutes into duration?

To convert from minutes to hours, divide the number of minutes by 60. For example, 120 minutes equals 2 hours because 120/60=2.


1 Answers

Use the divmod() function:

'{:02d}:{:02d}'.format(*divmod(minutes, 60))

Here divmod() divides the minutes by 60, returning the number of hours and the remainder, in one.

Demo:

>>> minutes = 135
>>> '{:02d}:{:02d}'.format(*divmod(minutes, 60))
'02:15'
like image 174
Martijn Pieters Avatar answered Oct 04 '22 20:10

Martijn Pieters