python-3.x - 时间不能在过去的条件Python中设置
问题描述
我需要做什么。 我需要这个程序不允许用户输入过去的日期。当我按目前的方式尝试时,我收到以下错误消息。TypeError:“datetime.datetime”和“str”的实例之间不支持“<”。
from datetime import datetime
from datetime import date
def addNewItems():
end = 4
while end == 4:
ToDoList = [ ]
Name = input("Enter the name of your task")
dateIn = input("Enter the task completion date. yyyy/mm/dd HH:MM:SS")
date = datetime.strptime(dateIn, "%Y/%m/%d %H:%M:%S")
now = datetime.now()
now_ = now.strftime("%d/%m/%Y %H:%M:%S")
if date < now_:
print("Time entered is in the past! Select options again")
continue
if Name in ToDoList:
print("Task already exists! Select options again")
continue
if date < now_ and Name not in ToDoList:
ToDoList.append(Name, date)
print("Task Added Sucessfully")
break
解决方案
您实际上需要两个datetime
对象才能<
直接使用比较。
你只需要比较date
with now
,而不是date
withnow_
就可以做你想做的事。
只是一个建议。您是date
从datetime
库中导入的,因此如果您打算date
在代码中的其他位置调用原始变量,则应避免创建具有相同名称的变量
推荐阅读
- c - 为什么周期性中断会有时间差异?
- ios - 如何使用 ObservedObject 作为 Picker 中的选择以及 SwiftUI 中的默认选择
- javascript - 联系表格提交电子邮件不发送
- javascript - 如何在 Node.js 上将函数从一个文件导出到另一个文件?
- javascript - 如何在提交 RobinHerbots / Inputmask 时取消屏蔽
- node.js - 尝试实现 NodeJS Gmail API 示例
- jquery - div 上的样式阻止触发 jquery 事件
- ruby-on-rails - 通过数据库中的 url 在 rails 中显示视频
- ios - Crashlytics:没有缓存设置 | 跳过报告
- javascript - 防止动态添加的选择改变其他 div 行为