[英]Converting and comparing 2 datetimes
我需要幫助,嘗試將字符串轉換為日期時間,然后進行比較以查看其是否少於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")))
被注釋掉的部分是我在時間上所做的,而其他部分是在日期時間上。
該錯誤發生在我嘗試將列表中的每個時間與當前時間進行比較的那一行,但是它將它們作為字符串而不是日期時間,並且不會減去它們,所以我可以對它們進行比較。 (在底部的for循環中。)
確實,不要轉換回字符串,而是使用datetime
對象。 如錯誤消息str - str
所指出, str - str
不是已定義的操作(從另一個字符串中減去一個字符串是什么意思?):
"s" - "s" # TypeError
而是使用datetime.now()
初始化timeNow
, datetime
實例支持減法。 第二個建議是,從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
我猜是你在追求什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.