Reputation: 326
I am calculating the time differance between api and system time, the code is working correctly, but showing incorrect result.
url="Some url"
for sec in range(30): #30 times hitting
time.sleep(1) #time delay of 1 seconds, 30 hits ,2 sec so 60 second totally
r = requests.get(url, params={}, headers = headers) # hitting the url after 2 seconds
reqres = json.loads(r.text)
time_in_api=reqres['last_updated_at_time']
time_in_api=time.ctime(time_in_api/1000000)
time_in_api_readable=datetime.datetime.strptime(str(time_in_api), "%a %b %d %H:%M:%S %Y")
our_time=datetime.datetime.now()
our_time = our_time.replace(microsecond=0)
# calculation of time differance
timediff=time_in_api_readable-our_time
print(timediff,time_in_api_readable,our_time)
and the output is,
0:00:02 2021-05-20 21:04:34 2021-05-20 21:04:32
0:00:00 2021-05-20 21:04:34 2021-05-20 21:04:34
0:00:01 2021-05-20 21:04:38 2021-05-20 21:04:37
0:00:00 2021-05-20 21:04:39 2021-05-20 21:04:39
0:00:01 2021-05-20 21:04:42 2021-05-20 21:04:41
-1 day, 23:59:59 2021-05-20 21:04:42 2021-05-20 21:04:43
0:00:01 2021-05-20 21:04:47 2021-05-20 21:04:46
-1 day, 23:59:59 2021-05-20 21:04:47 2021-05-20 21:04:48
0:00:01 2021-05-20 21:04:52 2021-05-20 21:04:51
-1 day, 23:59:58 2021-05-20 21:04:52 2021-05-20 21:04:54
-1 day, 23:59:55 2021-05-20 21:04:52 2021-05-20 21:04:57
-1 day, 23:59:53 2021-05-20 21:04:52 2021-05-20 21:04:59
-1 day, 23:59:50 2021-05-20 21:04:52 2021-05-20 21:05:02
-1 day, 23:59:47 2021-05-20 21:04:52 2021-05-20 21:05:05
-1 day, 23:59:44 2021-05-20 21:04:52 2021-05-20 21:05:08
Upvotes: 1
Views: 158
Reputation: 3438
This seems like an issue with human reading a "timedelta" object. You may consider "total_seconds()" to solve your problem.
import datetime
TimeNow = datetime.datetime.now()
TimeNow = TimeNow.replace(microsecond = 0)
TimeTenSecondsFromNow = TimeNow + datetime.timedelta(seconds = 10)
print ('TimeNow', TimeNow)
print ('TimeTenSecondsFromNow', TimeTenSecondsFromNow)
TimeDiff = TimeNow - TimeTenSecondsFromNow
print ('TimeDiff', TimeDiff)
DiffTotalSeconds = TimeDiff.total_seconds()
print ('DiffTotalSeconds', DiffTotalSeconds)
Output:
>>> TimeNow 2021-05-20 12:43:26
>>> TimeTenSecondsFromNow 2021-05-20 12:43:36
>>> TimeDiff -1 day, 23:59:50
>>> DiffTotalSeconds -10.0
Upvotes: 1