[英]comparing a unicode type and str type date in python
我正在嘗試比較從日期類型HTML輸入元素收到的日期和當前日期。
這是我的Python代碼。
deadline = request.POST.get('deadline', '')
today = datetime.date.today().strftime("%B %d, %Y")
print type(deadline)
print type(today)
if deadline > today:
task_obj = Task(user=request.user, name=name, deadline=deadline)
task_obj.save()
return HttpResponseRedirect(reverse('tasks'))
else:
return HttpResponse('Deadline cannot be before current date.')
print type(deadline)
輸出<type 'unicode'>
而print type(today)
輸出<type 'str'>
。 如何在Python中比較這兩個?
在Python 2中,如果unicode字符串不包含ASCII代碼點以外的任何其他內容,則可以直接比較它們:
if deadline == today:
Python將隱式編碼unicode字符串。 由於您的日期不是ISO8601格式的,因此您只能進行這種方式的相等性測試; 您無法測試一個大於或小於另一個,因為您是按字典排序順序比較字符串!
您確實需要將HTML unicode值解析為datetime
對象,然后將其進行比較:
today = datetime.date.today()
deadline = datetime.datetime.strptime(deadline, "%B %d, %Y").date()
if deadline > today:
現在,您正在比較datetime.date()
對象,這實際上使您可以按日期測試相對排序。
您可以使用此:
if deadline==today:
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.