Peter
Peter

Reputation: 91

How get hours:minutes

I have a script here (not my own) which calculates the length of a movie in my satreceiver. It displays the length in minutes:seconds

I want to have that in hours:minutes

What changes do I have to make?

This is the peace of script concerned:

if len > 0:
    len = "%d:%02d" % (len / 60, len % 60)
else:
    len = ""

res = [ None ]

I already got the hours by dividing by 3600 instead of 60 but can't get the minutes...

Thanks in advance

Peter

Upvotes: 9

Views: 26778

Answers (4)

Marc Belmont
Marc Belmont

Reputation: 584

You can use timedelta

from datetime import timedelta
str(timedelta(minutes=100))[:-3]
# "1:40"

Upvotes: 20

wallyk
wallyk

Reputation: 57764

hours = secs / 3600
minutes = secs / 60 - hours * 60

len = "%d:%02d" % (hours, minutes)

Or, for more recent versions of Python:

hours = secs // 3600
minutes = secs // 60 - hours * 60

len = "%d:%02d" % (hours, minutes)

Upvotes: 13

Anentropic
Anentropic

Reputation: 33823

There is a nice answer to this here https://stackoverflow.com/a/20291909/202168 (a later duplicate of this question)

However if you are dealing with timezone offsets in a datetime string then you need to also handle negative hours, in which case the zero padding in Martijn's answer does not work

eg it would return -4:00 instead of -04:00

To fix this the code becomes slightly longer, as below:

offset_h, offset_m = divmod(offset_minutes, 60)
sign = '-' if offset_h < 0 else '+'
offset_str = '{}{:02d}{:02d}'.format(sign, abs(offset_h), offset_m)

Upvotes: 0

jcdyer
jcdyer

Reputation: 19145

So len the number of seconds in the movie? That's a bad name. Python already uses the word len for something else. Change it.

def display_movie_length(seconds):
    # the // ensures you are using integer division
    # You can also use / in python 2.x
    hours = seconds // 3600   

    # You need to understand how the modulo operator works
    rest_of_seconds = seconds % 3600  

    # I'm sure you can figure out what to do with all those leftover seconds
    minutes = minutes_from_seconds(rest_of_seconds)

    return "%d:%02d" % (hours, minutes)

All you need to do is figure out what minutes\_from\_seconds() is supposed to look like. If you're still confused, do a little research on the modulo operator.

Upvotes: 1

Related Questions