Seconds to timestamp, if-else condition, MM:SS and HH:MM:SS

Advertisements

The exercise is to convert input seconds and have output in timestamp.
If seconds is 61, the output should be "1:01" and if the input is 3600, the output should be ‘1:00:00’.

I wrote the code below but it works when I write in the input up to seconds=3599. Above that, the output turns out to be ‘0:00’ and not ‘1:00:00’. If I remove the if else condition and only return "%1d:%02d:%02d" % (hour, minutes, seconds), the output from seconds=61 will be ‘0:01:01’ and not ‘1:01’.

How should I solve it?

def seconds_to_timestamp(seconds):
hour= seconds // 3600
seconds%= 3600
minutes=seconds//60
seconds%=60

if seconds<=3599:
    return "%1d:%02d" % (minutes, seconds)
   
else:
    return "%1d:%02d:%02d" % (hour, minutes, seconds)

>Solution :

The issue with your current implementation is you are taking mod of seconds with 3600. Now whatever the value would be of the seconds it will always become less than 3600. And so, every time only your if condition will be satisfied. Following code solves your issue

def seconds_to_timestamp(seconds):
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60

    if hour > 0:
        return "%d:%02d:%02d" % (hour, minutes, seconds)
    else:
        return "%d:%02d" % (minutes, seconds)

Leave a ReplyCancel reply