Exercise 1.3: Time and type conversions


Using the techniques you have learned in the first day of bootcamp, generate a time stamp (like 13:29:45 for nearly half past one in the afternoon) for the time that is 63,252 seconds after midnight. Start with this statement:

[1]:
seconds_past_midnight = 63252

After that statement, the only numeric keys you should need or want to push are 0, 2 or 3, and 6.

Solution


To get the number of hours, we floor divide by 3600. To get the number of minutes, we take the modulus of division by 3600, and then divide that by 60. Finally, the seconds are what is left over when we divide by 60.

[2]:
hours = seconds_past_midnight // 60**2
minutes = (seconds_past_midnight % 60**2) // 60
seconds = seconds_past_midnight % 60

Now that we have these, we concatenate a string together.

[3]:
time_str = str(hours) + ':' + str(minutes) + ':' + str(seconds)

print(time_str)
17:34:12

There are much more elegant ways of doing these two operations, including using string methods that we will learn in coming lessons. For most applications using time stamps, you would use the datetime module of the standard library.

Computing environment

[4]:
%load_ext watermark
%watermark -v -p jupyterlab
Python implementation: CPython
Python version       : 3.9.12
IPython version      : 8.3.0

jupyterlab: 3.3.2