Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading