Python 2.7.6 help with modules

Chris Angelico rosuav at gmail.com
Sun Feb 9 07:30:11 CET 2014


On Sun, Feb 9, 2014 at 5:00 PM, Scott W Dunning <swdunning at cox.net> wrote:
> On Feb 8, 2014, at 6:46 PM, Chris Angelico <rosuav at gmail.com> wrote:
>
> That's certainly effective. It's going to give you the right result. I
> would be inclined to start from the small end and strip off the
> seconds first, then the minutes, etc, because then you're working with
> smaller divisors (60, 60, 24, 7 instead of 604800, 86400, 3600, 60);
> most people will understand that a week is 7 days, but only people who
> work with DNS will know that it's 604800 seconds. But both work.
>
>
> How would working from the small end (seconds) first and going up to weeks
> allow me to work with the smaller divisors?  Wouldn’t it still have to be in
> seconds?

Here's how to do it from the small end up:

time = int(raw_input("Enter number of seconds: "))
seconds = time % 60
time /= 60
minutes = time % 60
time /= 60
hours = time % 24
time /= 24
days = time % 7
time /= 7
weeks = time
# Alternative way to format for display:
print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds))

Enter number of seconds: 123456789
204 weeks, 0 days, 21:33:09

Produces the same result, has the same amount of division in it, but
the time keeps shifting down: after the first pair, it's a number of
minutes, after the second pair it's a number of hours, and so on.

By the way, here's the divmod version of the above code:

time = int(raw_input("Enter number of seconds: "))
time, seconds = divmod(time, 60)
time, minutes = divmod(time, 60)
time, hours = divmod(time, 24)
weeks, days = divmod(time, 7)
print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds))

It's now fairly clear what's going on. Each time unit is on the same
line as the number of that time unit that make up the next one.

The same thing, going down, looks like this:

seconds = int(raw_input("Enter number of seconds: "))
weeks, seconds = divmod(seconds, 604800)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds))

Also fairly clear; each time unit is on the same line as the number of
seconds that make up that unit. Both methods make sense, in their own
way.

ChrisA



More information about the Python-list mailing list