在Python中比较Unicode类型和字符串类型的日期
我正在尝试比较一个从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中比较这两个呢?
2 个回答
0
你可以使用这个:
if deadline==today:
...
3
在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()
对象,这样就能根据日期的先后顺序进行比较了。