简体   繁体   English

转换和比较2个日期时间

[英]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. 我需要帮助,尝试将字符串转换为日期时间,然后进行比较以查看其是否少于3天。 I have tried both with the time class, as well as the datetime class, but I keep getting the same error: 我已经尝试了time类和datetime类,但是我一直遇到相同的错误:

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.) (在底部的for循环中。)

Indeed, don't convert back to strings and instead work with datetime objects. 确实,不要转换回字符串,而是使用datetime对象。 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?): 如错误消息str - str所指出, str - str不是已定义的操作(从另一个字符串中减去一个字符串是什么意思?):

"s" - "s" # TypeError

Instead, initialize timeNow with datetime.now() , datetime instances support subtracting. 而是使用datetime.now()初始化timeNowdatetime实例支持减法。 As a second suggestion, subtract ele from timeNow and not timeNow from ele : 第二个建议是,从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")))

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. 我猜是你在追求什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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