简体   繁体   中英

comparing datetime.timedelta and datetime.time in python

I have this code where I execute a sql query and get two TIME fields. Now I want to compare these two with other time type field. My current code is below

import datetime

def comp(time1,time2):

        start_time_obj = datetime.datetime.strptime(time1, '%H:%M').time()
        end_time_obj = datetime.datetime.strptime(time2, '%H:%M').time()

        sql_select2 = "select TIME(Start_Time), TIME(End_Time) from table1"
        result2 = cur.execute(sql_select2)

        resultSet2 = cur.fetchall()
        for Start_Time,End_Time in resultSet2:
             if (Start_Time <= start_time_obj <= End_Time) or (Start_Time <= end_time_obj <= End_Time):
                    print("Great!")
                    continue

if __name__ == '__main__':
    comp("08:00","10:00")

When I execute this I get error as TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'datetime.time' . How to remove this?

Note : this is the sample field structure in database - '2017-06-16 08:06:00' for both Start_Time and End_Time. What I want to do is compare the time part in the above field with the time coming as a parameter

What if you do

 start_time_obj = datetime.datetime.strptime(time1, '%H:%M').date()
 end_time_obj = datetime.datetime.strptime(time2, '%H:%M').date()

using .date() instead of .time()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM