+ 1

Is this code good ? what are you best suggestions ?

I wanted to practice python from a book called Think Python, and there was an exercise asking to 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. I did my own code down below, I just wanted to have confirmation if it's working correctly and if you guys have an advice for a better code because I'm a beginner and I'm trying to practice. def to_day_in_hours(): import time t = time.time() print("The current time is : \n",t) days = t // ( 3600 * 24 ) print("Days since epoch are : \n",days) minutes = t // 60 print("The minutes are : \n",minutes) hours = minutes // 60 print("The hours are : \n",hours) print( int(hours % 60), ":", int(minutes % 60),":", int(t % 60),"on",int(days),"Days since epoch") to_day_in_hours()

9th Aug 2020, 3:12 AM
Louai Belfounes
Louai Belfounes - avatar
7 Respostas
+ 2
It is bad practice to import inside a function. As for if the code is working or not, it is best to try it yourself using different inputs and see if the result is the expected output.
9th Aug 2020, 3:24 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Aymane Boukrouh Why is it bad to import inside a function ? Also, since this code doesn't take any inputs from the user, i definitely get an output, but i'am not sure if it's the right one i'am expecting.
9th Aug 2020, 3:25 AM
Louai Belfounes
Louai Belfounes - avatar
+ 2
Louai Belfounes it's just a general rule for writing a clean code. If another user is checking your code then he'll be expecting to see all imported modules and libraries in the top of the file. Another thing I forgot to mention is that you don't need \n inside your print statements, python automatically adds it to the end or your printed string (unless you purposely want a blank line between different prints). Finally, about the results, you should get UTC as your time output (03:31AM now).
9th Aug 2020, 3:30 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Louai Belfounes in your last print statement it should be hours%24 not hours%60, that will give your the result in military time. To convert to AM/PM, just use an if statement, if hours%12<12 then AM else PM
9th Aug 2020, 3:44 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
No problem, keep up the good work!
9th Aug 2020, 3:48 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Aymane Boukrouh - Thanks a lot, i'll make sure to add from now on the import in the top of the file. - I get the output as 15:33:22 while when i check on google UTC it gives 03:33:22 It's not 100% correct i guess, the AM/PM thing is different. any suggestion ?
9th Aug 2020, 3:35 AM
Louai Belfounes
Louai Belfounes - avatar
+ 1
Aymane Boukrouh Smart Move ! Thanks man, i really appreciated your help.
9th Aug 2020, 3:48 AM
Louai Belfounes
Louai Belfounes - avatar