Python code challenge

Discuss other programming languages besides AutoHotkey
User avatar
derz00
Posts: 497
Joined: 02 Feb 2016, 17:54
Location: Middle of the round cube
Contact:

Python code challenge

01 Nov 2017, 10:03

(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.
try it and see
...
User avatar
Capn Odin
Posts: 1352
Joined: 23 Feb 2016, 19:45
Location: Denmark
Contact:

Re: Python code challenge

19 Nov 2017, 21:20

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)}")
Please excuse my spelling I am dyslexic.
User avatar
derz00
Posts: 497
Joined: 02 Feb 2016, 17:54
Location: Middle of the round cube
Contact:

Re: Python code challenge

20 Nov 2017, 09:34

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
try it and see
...

Return to “Other Programming Languages”

Who is online

Users browsing this forum: No registered users and 0 guests