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!
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.
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.
To convert from minutes to hours, divide the number of minutes by 60. For example, 120 minutes equals 2 hours because 120/60=2.
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'
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