I'm trying to code a Python script for 'Enter the number of Seconds' and get results in weeks, days, hours, minutes and seconds. Here is what I have, but I am not getting the correct answers. What am I doing wrong?
seconds = raw_input("Enter the number of seconds:")
seconds = int(seconds)
minutes = seconds/60
seconds = seconds % 60
hours = minutes/60
hours = seconds/3600
minutes = minutes % 60
days = hours/24
days = minutes/1440
days = seconds/86400
hours = hours % 60
hours = minutes % 60
hours = seconds % 3600
weeks = days/7
weeks = hours/168
weeks = minutes/10080
weeks = seconds/604800
days = days % 1
days = hours % 24
days = minutes % 1440
days = seconds % 86400
weeks = weeks % 1
weeks = days % 7
weeks = hours % 168
weeks = minutes % 10080
weeks = seconds % 604800
print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds'
Just from the basic conversion principles:
weeks = seconds / (7*24*60*60)
days = seconds / (24*60*60) - 7*weeks
hours = seconds / (60*60) - 7*24*weeks - 24*days
minutes = seconds / 60 - 7*24*60*weeks - 24*60*days - 60*hours
seconds = seconds - 7*24*60*60*weeks - 24*60*60*days - 60*60*hours - 60*minutes
A bit of a less noisy way of doing the same thing:
weeks = seconds / (7*24*60*60)
seconds -= weeks*7*24*60*60
days = seconds / (24*60*60)
seconds -= days*24*60*60
hours = seconds / (60*60)
seconds -= hours*60*60
minutes = seconds / 60
seconds -= minutes *60
A cleaner version of again the same thing with divmod
function which returns both division result and remainder in a tuple (division, remainder)
:
weeks, seconds = divmod(seconds, 7*24*60*60)
days, seconds = divmod(seconds, 24*60*60)
hours, seconds = divmod(seconds, 60*60)
minutes, seconds = divmod(seconds, 60)
Basically, this solution is closest to your attempt since this is what divmod
does:
weeks, seconds = divmod(seconds, 7*24*60*60)
equivalent to
weeks = seconds / (7*24*60*60)
seconds = seconds % (7*24*60*60)
Here we are essentially finding the number of whole weeks in our time and keeping what is left after these weeks are removed.
And also you can go from the other end to make it even prettier:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
The idea behind this is that the number of seconds in your answer is the remainder after dividing them in minutes; minutes are the remainder of dividing all minutes into hours etc... This version is better because you can easily adjust it to months, years, etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With