简体   繁体   中英

Converting and comparing 2 datetimes

I need help trying to convert a string to datetime, then comparing it to see if it is less than 3 days old. I have tried both with the time class, as well as the datetime class, but I keep getting the same error:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

here is the code I have tried:

def time_calculation():
    time1 = "2:00 PM 5 Oct 2016"
    time2 = "2:00 PM 4 Oct 2016"
    time3 = "2:00 PM 1 Oct 2016"
    timeNow = time.strftime("%Y%m%d-%H%M%S")
    #newtime1 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time1, "%I:%M %p %d %b %Y"))
    newtime1 = datetime.strptime(time1, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S")
    print("the new time1 is {}".format(newtime1))
    #newtime2 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time2, "%I:%M %p %d %b %Y"))
    newtime2 = datetime.strptime(time2, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S")
    print("the new time2 is {}".format(newtime2))
    #newtime3 = time.strftime("%Y%m%d-%H%M%S", time.strptime(time3, "%I:%M %p %d %b %Y"))
    newtime3 = datetime.strptime(time3, "%I:%M %p %d %b %Y").strftime("%Y%m%d-%H%M%S")
    print("the new time3 is {}".format(newtime3))
    timeList = []
    timeList.append(newtime1)
    timeList.append(newtime2)
    timeList.append(newtime3)

    for ele in timeList:
        deltaTime = ele - timeNow
        if deltaTime.days < 4:
            print("This time was less than 4 days old {}\n".format(ele.strftime("%Y%m%d-%H%M%S")))

the commented out parts are what I did with time, while the others are with datetime.

the error happens at the line where I try to compare the current time with each time in the list, but it takes them as strings instead of datetimes and won't subtract them so I can compare them. (In the for loop at the bottom.)

Indeed, don't convert back to strings and instead work with datetime objects. As noted in the error message str - str isn't an operation that's defined (what does it mean to subtract a string from another?):

"s" - "s" # TypeError

Instead, initialize timeNow with datetime.now() , datetime instances support subtracting. As a second suggestion, subtract ele from timeNow and not timeNow from ele :

def time_calculation():
    # snipped for brevity
    timeNow = datetime.now()

    # snipped

    for ele in timeList:
        deltaTime = timeNow - ele
        if deltaTime.days < 4:
            print("This time was less than 4 days old {}\n".format(ele.strftime("%Y%m%d-%H%M%S")))

Prints out:

time_calculation()
the new time1 is 2016-10-05 14:00:00
the new time2 is 2016-10-04 14:00:00
the new time3 is 2016-10-01 14:00:00
This time was less than 4 days old 20161005-140000

This time was less than 4 days old 20161004-140000

Which I'm guessing is what you were after.

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