Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to weeks-days-hours-minutes-seconds in Python

Tags:

python

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'
like image 924
sjud9227 Avatar asked Dec 19 '22 19:12

sjud9227


1 Answers

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...

like image 137
sashkello Avatar answered Jan 06 '23 09:01

sashkello