我想比較兩個日期以回傳一些東西。我已經嘗試了很長時間。所以我想要的是:
我有一個名為 current_date = date.today 的變數,現在我想將 current_date 與另一個 datefield 變數進行比較。我試過這段代碼:
current_date = date.today()
# I am getting this another date from a html input type date
another_date = request.POST.get("date")
if current_date > another_date:
return True
else:
return False
但我收到一個錯誤
'<' not supported between instances of 'datetime.date' and 'str'
如何解決這個問題?
uj5u.com熱心網友回復:
因為您正在將字串與 datetime.date 物件進行比較。喜歡比較
23 > "hello world"
嘗試轉換從前一種方法收到的字串。關注另一個討論
uj5u.com熱心網友回復:
這個:
another_date = request.POST.get("date")
以字串格式為您提供日期,例如“2022-06-16”,并datetime.date給出datetime.date(2022, 06, 16). 你不能那樣比較它,你必須將一個轉換為另一個型別(或其他方式)。
我建議:
current_date = date.today().strftime("%Y-%m-%d")
another_date = request.POST.get("date")
我假設'date'看起來像year-month-day。
uj5u.com熱心網友回復:
表單中的日期欄位將為您提供一個格式為YY-MM-DD. 這種格式是字串str,不能與datetime物件進行比較。因此,出現錯誤的原因是:
'datetime.date' 和 'str' 的實體之間不支持 '<'
您可以創建一個可重用的函式來比較日期,例如:
def dates_equal(d1, d2):
if d1 == d2:
return True
else:
return False
然后在你的代碼中的某個地方,你可以這樣稱呼它......
current_date = date.today()
# Getting the string version of the date object
current_date = current_date.strftime("%Y-%m-%d")
# I am getting this another date from a html input type date
another_date = request.POST.get("date")
# Calling the date comparing method here...
if dates_equal(current_date, another_date):
# do something here...
else:
# do something else...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/492200.html
標籤:Python html python-3.x django
上一篇:獲取子節點
下一篇:單選按鈕的多行標簽
