Working with Time
The time
module
Let's go straight in and see some examples of what the time
module can do:
import time
time.time()
1607080140.0588841
Scary! This was the epoch, also known as Unix time, at the moment the code was executed, and is the number of seconds since midnight on January 1st, 1970 in UTC / GMT timezone.
Friendlier time formats
billionth = time.localtime(1000000000)
billionth
time.struct_time(tm_year=2001, tm_mon=9, tm_mday=9, tm_hour=2, tm_min=46, tm_sec=40, tm_wday=6, tm_yday=252, tm_isdst=1)
- the
localtime()
function, for example, takes an epoch and returns astruct_time
object which has various attributes likely to be of use
time.strftime("%a, %d %b %Y %H:%M:%S %Z", billionth)
'Sun, 09 Sep 2001 02:46:40 BST'
- the
.strftime()
or 'string formatted time method can be used to make time values more human-readable, with great flexibility over the formatting
Code walkthrough
Let's make use of the ability to record timestamps in our Spotter
class definition, to automatically renew the access_token
if it has expired.
Fork the repl if you'd like to try it out yourself, remembering to create your own new .env
file.
Nothing new to see in main.py
, but there is in spotter.py
, where we have imported time
and made changes to the get_token()
and get_item()
methods.
get_token()
...
self.token_request_timestamp = time.time()
...
- before making the API call, we log the current time
...
self.token_expiry = self.token_request_timestamp + token_info['expires_in']
self.token_expiry_local = time.strftime("%a, %d %b %Y %H:%M:%S %Z", \
time.localtime(self.token_expiry))
...
- we fetch the
'expires_in'
value from the response and calculate the time the token will expire, assigning the result to the.token_expiry
attribute of the object - we also assign a more readable version to
token_expiry_local
Recording the time before making the API call and then adding the expires_in
value protects us from the possibility of any 'gap' due to latency between the server response and our program receiving it.
get_item()
if time.time() > self.token_expiry:
print('Getting new token...')
self.get_token()
- if the current time when
get_item()
is called is later than thetoken_expiry
,get_token()
will be called again and thetoken
andtoken_expiry
will be updated
As a result, we can use the get_item()
method of any instance of Spotter
for as long as we like, without needing to manually renew the token or create a new object to make more API calls.