转换和比较2个日期时间

时间:2016-10-05 22:48:46

标签: python python-3.x datetime

我需要帮助尝试将字符串转换为日期时间,然后比较它以查看它是否少于3天。我已经尝试了时间类和日期时间类,但我一直得到同样的错误:

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

这是我尝试过的代码:

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")))

注释掉的部分是我用时间做的,而其他部分是用datetime。

错误发生在我尝试将当前时间与列表中的每次时间进行比较的行,但它将它们作为字符串而不是日期时间,并且不会减去它们以便我可以比较它们。 (在底部的for循环中。)

1 个答案:

答案 0 :(得分:1)

确实,不要转换回字符串,而是使用datetime个对象。如错误消息中所述,str - str不是一个已定义的操作(从另一个字节中减去字符串是什么意思?):

"s" - "s" # TypeError

相反,使用timeNow初始化datetime.now()datetime个实例支持减法。作为第二个建议,从ele中减去timeNow而不从timeNow减去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")))

打印出来:

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

我猜测的就是你所追求的。

相关问题