Jarmos
Jarmos

Reputation: 456

Understanding Allen Downey's 'Think Python' Section 5.14 Exercise #1

Link to the exercise can be accessed here - Section 5.14 Exercise #1

Quoting the question:

Exercise 1
...

Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.

A possible solution is available here - Solution

The solution provided above seems easy to understand but I'm confused with the calculations/formulae to convert epoch time to a normal time of day. These lines are confusing me the most:

hours = (epoch % seconds_in_a_day) // seconds_in_an_hour + 8
minutes = (epoch % seconds_in_a_day) % seconds_in_an_hour // seconds_in_a_minute
seconds = (epoch % seconds_in_a_day) % seconds_in_an_hour % seconds_in_a_minute

My question is, why is the remainder from dividing seconds_in_a_day from epoch is divided by seconds_in_an_hour and then an 8 is added to the result. I've similar confusion with the minutes and seconds variable as well. I'm trying to understand the logic behind such calculation but it's quite confusing.

Upvotes: 1

Views: 578

Answers (2)

Fengy
Fengy

Reputation: 21

I too have been working through the book trying to learn some python coding and today I encountered this question. And here is my attempt,

total_secs  = time.time()
seconds = total_secs % 60
minutes = (total_secs // 60) % 60
hours = (total_secs // 3600) % 24
days = total_secs // (3600 * 24)

The logic behind this is, the seconds is the remainder of total seconds divided by the number of seconds in a minute, and the minutes is the remainder of total minutes divided by the number of minutes in an hour, by this logic we can get the hours and days in the same fashion.

The code is much simpler to read and easier to understand, hopefully it can clear some confusion for the future python beginner who reads this.

Upvotes: 2

avayert
avayert

Reputation: 684

Because the epoch is seconds in total since 1970, we only want to observe the amount of seconds elapsed today. This gives the first part of each formula,(epoch % seconds_in_a_day).

Now since we have an amount of seconds that has elapsed today, we can divide it by the amount of seconds in an hour to get the amount of hours. 8 is added here to the result because Beijing's timezone is UTC+8.

Since we also have seconds within a day, for hours and seconds we repeat the logic used for days. If we know that n seconds have elapsed since the start of today, we can modulo this time by the amount of seconds in a single hour to get the "remainder" amount of seconds that have elapsed in the last non-complete hour. Now we just divide it by seconds_in_a_minute to turn seconds into minutes.

The same logic applies for the seconds.

Upvotes: 2

Related Questions