Need help comparing datetime objects derived from a dateframe in a conditional statement

skidwiz :

I have a csv file that contains the names of personnel and the times when they swipe their badges at work. I am trying to write a program that will evaluate the dateframe and pull the first time they swiped their badges and see if that time was more than 1 hour ago. The csv file looks like this.

,EmpName,PIN,swiped_in,datetime_in
1,Bob,1234,True,2020-03-03 07:20:02.909810

I then use this code to read in the file and conduct the operations:

def check_logins(employee_name):
    swiped_in = False

    try:
        with open('analytics.csv', 'r+') as analytics:
            analyticsdf = pd.read_csv(analytics)
            analyticsdf['datetime_in'] = pd.to_datetime(analyticsdf['datetime_in'])
            check_time = (datetime.today() - timedelta(hours=1))
            in_time= (datetime.today() - analyticsdf.loc[analyticsdf['UserName'] == employee_name, 'datetime_in'].iloc[0])
            if username in reg_usersdf.values:
                if analyticsdf.loc[analyticsdf['EmpName'] == employee_name, 'swiped_in'].iloc[0]:
                    print("Condition is True")
                    if in_time > check_time:
                        print("Time is 1 hour old")
                        swiped_in = False
                        analyticsdf.loc[analyticsdf['EmpName'] == employee_name, 'swiped_in'].iloc[0] = swiped_in
                        analyticsdf.to_csv('analytics.csv')
                        return swiped_in
                    else:
                        swiped_in = True
                        return swiped_in
    except FileNotFoundError:
            print('File not found.')  

    return swiped_in

My problem is between my 2nd and 3rd conditional statements. I first check to see if the employee exists in the csv file, then I check that he/she has swiped their badge. Finally, I check if the last badge swipe was more than 1 hour ago. However, I never enter the "Time is 1 hour old" check. Instead, I get a TypeError saying "TypeError: Cannot compare type Timedelta with type datetime."

How can I convert the times properly in order to check if the first time is more than 1 hour from the current time?

Young Wook Baek :

From your code, check_time is datetime: 1 hour prior to the current time

check_time = (datetime.today() - timedelta(hours=1))

On the other hand, in_time is timedelta: time duration between the current time and the last swipe

in_time= (datetime.today() - analyticsdf.loc[analyticsdf['UserName'] == employee_name, 'datetime_in'].iloc[0])

That's why you are getting a TypeError since you are trying to compare the actual time and the duration

if in_time > check_time:

So what you WANT is to see if the duration is greater than 1 hour, as the following:

if in_time > timedelta(hours=1):

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170537&siteId=1