Venkat kamal
Venkat kamal

Reputation: 279

Calculating the time passed after specific operation

I wants to calculate the time since two sets become equal. I use time.time() to calculate the time. But whenever i calculate the time when the sets are equal, it returns time as 1520763846.19. I want to calculate the time from which both sets become equal and have to perform some downstream operation. Any help will be appreciated?

dis_cars,forbid_cars are two sets

def cars_on_road(dis_cars,forbid_cars):
    if len(forbid_cars) > 0 and dis_cars == forbid_cars:
        time_calculate = time.time()
        print "time_calculate" + str(time_calculate)

Upvotes: 2

Views: 52

Answers (2)

WorkShoft
WorkShoft

Reputation: 440

def __init__(self):
    self.last = time.time() #Initialization instant

def cars_on_road(self, dis_cars,forbid_cars):
    if len(forbid_cars) > 0 and dis_cars == forbid_cars:
        time_calculate = time.time() - self.last #Difference between self.last and the instant the sets became equal
        print "time_calculate" + str(time_calculate)
        self.last = time.time() #Do this if this method will be called again

Upvotes: 1

jpp
jpp

Reputation: 164693

Here is one way using datetime module.

import time
from datetime import datetime

def time_check(dis_cars, forbid_cars):
    if len(forbid_cars) > 0 and dis_cars == forbid_cars:
        time_calculate = datetime.now()
        return time_calculate
    else:
        return None

dis_cars = {'A', 'B', 'C'}
forbid_cars = {'C', 'B', 'A'}

check_time = time_check(dis_cars, forbid_cars)

time.sleep(3)

time_change_since_match = (datetime.now() - check_time).total_seconds()
# 3.000125

Explanation

  • Your functions should return a value, which you can store in a variable for later use. Printing a value does not store the value in memory.
  • Later you can access this variable again and use methods such as total_seconds() to return a time difference in seconds.

Upvotes: 1

Related Questions