首页 > 解决方案 > 时间不能在过去的条件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

标签: python-3.x

解决方案


您实际上需要两个datetime对象才能<直接使用比较。

你只需要比较datewith now,而不是datewithnow_就可以做你想做的事。

只是一个建议。您是datedatetime库中导入的,因此如果您打算date在代码中的其他位置调用原始变量,则应避免创建具有相同名称的变量


推荐阅读