转换和比较2个日期时间

2024-09-24 00:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助尝试将字符串转换为datetime,然后比较它以查看它是否少于3天。我在time类和datetime类中都尝试过,但我一直都会遇到相同的错误:

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循环中。)


Tags: formatfordatetimetime时间printstrftimestrptime
1条回答
网友
1楼 · 发布于 2024-09-24 00:29:59

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

"s" - "s" # TypeError

相反,使用datetime.now()初始化timeNowdatetime实例支持相减。第二个建议是,从timeNow中减去ele,从ele中减去timeNow

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

我猜这就是你想要的

相关问题 更多 >