Moortiii

Human Readable Time

Nov 28th, 2016
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. # This would probably be a lot easier to do using the timedate library and timedelta
  2. # or something along those lines, but I actually quite like this approach to the challenge.
  3.  
  4. # I originally had a variable called remainder that stored the number of seconds after each
  5. # subtraction, but quickly realized it was redundant, once "seconds" is smaller than 60, we
  6. # can simply return the seconds variable itself, as it will always fit the criteria.
  7.  
  8. def make_readable(seconds):
  9.     hours = 0  # A counter that tracks the number of hours
  10.     minutes = 0  # A counter that tracks the number of minutes
  11.    
  12.     while seconds >= 3600:  # Check that there is at least 1 hour worth of seconds left
  13.         seconds -= 3600  # Subtract exactly 1 hour from the amount of seconds
  14.         hours += 1  # Add 1 to the counter that tracks hours
  15.        
  16.     while seconds >= 60:  # Check that there is at least 1 minute worth of seconds left
  17.         seconds -= 60  # Subtract exactly 1 minute from the amount of seconds.
  18.         minutes += 1  # Add 1 to the counter that tracks minutes
  19.    
  20.     if hours < 10:
  21.         hours = "0" + str(hours)  # Some simple formatting to get the HH:MM:SS output we want
  22.     if minutes < 10:
  23.         minutes = "0" + str(minutes)  # Some simple formatting to get the HH:MM:SS output we want
  24.     if seconds < 10:
  25.         seconds = "0" + str(seconds)  # Some simple formatting to get the HH:MM:SS output we want
  26.    
  27.     return "{}:{}:{}".format(hours, minutes, seconds)  # Finally we return the formatted string
Advertisement
Add Comment
Please, Sign In to add comment