Page 1 of 1

Python code challenge

Posted: 01 Nov 2017, 10:03
by derz00
(Don't ask me for the solution, I don't know it)
(It's not so much about python syntax as about time and epoch, etc)
(Found in a book teaching Python concepts)
(This is one of the few exercises that didn't have a link to the solution)

Rules: Aren't any
Exercise 5.1. The time module provides a function, also named time, that returns the current
Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On
UNIX systems, the epoch is 1 January 1970.
>>> import time
>>> time.time()
1437746094.5735958
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.

Re: Python code challenge

Posted: 19 Nov 2017, 21:20
by Capn Odin
I'm pretty tired so the code is likely bad, at the very least it is inefficient.

Code: Select all

import time

ut = time.time()

days = ut // (60 * 60 * 24)

secToDay = ut % (60 * 60 * 24)
hour = secToDay // (60 * 60)
min  = secToDay // 60 - hour * 60
sec  = secToDay - hour * 60 * 60 - min * 60

print(f"Days: {int(days)}\nTime: {int(hour)}:{int(min)}:{int(sec)}")
Edit: I like this better.

Code: Select all

import time

ut = time.time()

days = ut / (60 * 60 * 24)
hour = days % int(days) * 24
min  = hour % int(hour) * 60
sec  = min % int(min) * 60

print(f"Days: {int(days)}\nTime: {int(hour)}:{int(min)}:{int(sec)}")

Re: Python code challenge

Posted: 20 Nov 2017, 09:34
by derz00
Very nice, thank you. I couldn't really proceed with the book without getting over this hump. Oh boy, programming does take a lot of mathematics. I find programming fascinating, but I see now that if I am to pursue it further, I will need more than casual interest. Thank you very much for doing this for me. :thumbup: I would not have been able to figure out that dividing the ut by (60 * 60 * 24) results in days. You're a genius!

Edit: Alright, thinking it through, 60 seconds * 60 minutes * 24 hours in a day is 86400 seconds in a day. Very clever :P