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.
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)
localtime()
function, for example, takes an epoch and returns a struct_time
object which has various attributes likely to be of usetime.strftime("%a, %d %b %Y %H:%M:%S %Z", billionth)
'Sun, 09 Sep 2001 02:46:40 BST'
.strftime()
or 'string formatted time method can be used to make time values more human-readable, with great flexibility over the formattingNothing 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()
...
...
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))
...
'expires_in'
value from the response and calculate the time the token will expire, assigning the result to the .token_expiry
attribute of the objecttoken_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()
get_item()
is called is later than the token_expiry
, get_token()
will be called again and the token
and token_expiry
will be updatedAs 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.