Welcome to StackOverflow! I've updated your script and added some notes:
seconds = int(input('Enter a number to convert to a formal timestamp: '))
hours = seconds // 3600 # there are 3600 seconds per hour
seconds -= hours * 3600 # don't double count seconds counted by hours
minutes = seconds // 60 # there are 60 seconds per minute
seconds -= minutes * 60 # don't double count seconds counted by minutes
time_string = "{}:{}:{}".format(hours, minutes, seconds)
print(time_string)
going through some of the lines individually:
seconds = int(input('Enter a number to convert to a formal timestamp: '))
I assume here that you are working in Python 3. If so, input
is exactly what we want. If you are in Python 2, however, input
does something slightly related and what we really want is something else - raw_input
. raw_input
was renamed input
when the move was made from 2 to 3. Either way, we pass whatever is input by the user to the int
function and convert it to an integer value.
time_string = "{}:{}:{}".format(hours, minutes, seconds)
"{}:{}:{}"
is a format string. You can read more about them in the Python docs. The pairs of curly brackets are each placeholders for the arguments passed to the format
method; the first brackets get replaced with the first argument hours
, the second pair gets replaced with the second argument minutes
, and so on.
If you are in Python 2, the code won't quite work as specified. Luckily, most of them can be backported to Python 2 by importing from the __future__
module; the only manual change would be switching input
to raw_input
in this case. Here's the same code, in Python 2:
from __future__ import print_function, division
seconds = int(raw_input('Enter a number to convert to a formal timestamp: '))
hours = seconds // 3600 # there are 3600 seconds per hour
seconds -= hours * 3600 # don't double count seconds counted by hours
minutes = seconds // 60 # there are 60 seconds per minute
seconds -= minutes * 60 # don't double count seconds counted by minutes
time_string = "{}:{}:{}".format(hours, minutes, seconds)
print(time_string)