0

我想阻止我的程序在一个日历日内多次运行和接受输入。有没有办法做到这一点?

我尝试在代码末尾导入日期并将其存储在变量中,然后在代码开头导入日期并进行比较,但是当然,运行代码时未定义代码末尾的变量首次。

import datetime

new_time = str(datetime.datetime.now())
new_time = new_time[8:10]
new_time = int(new_time)

while new_time == last_time:
    print("Please wait until tomorrow before entering a new value")





last_time = str(datetime.datetime.now())

last_time = last_time[8:10]
last_time = int(last_time)

使用这种方法,它除了第一次没有定义变量 last_time 时有效

4

1 回答 1

-1

通过将当前日期附加到文件中,您可以比较日历日的差异。

代码:

import datetime
new_day = int(datetime.datetime.now().strftime("%d"))
last_day = 0
with open("last_time.txt", "r") as f:
    lines = f.read().splitlines()
    last_day = lines[-1]

if new_day == int(last_day):
    print("Please wait until tomorrow before entering a new value")

with open("last_day.txt", "a+") as f:
    last_day = datetime.datetime.now().strftime("%d")
    f.write(last_day)

解释:

1. Create a text file(last_time.txt) and give the default day as when you are running the script for first time(as today(24))
2. get the new_day as day from datetime.now() and convert into an integer.
3. By default keeping the last_day=0 or you can give the current date for first time
4. Reading the last time from the last line of the file
5. If new_day and last_day are equal, then print the message to the user.
6. Fetch the current day as last_day and write to a file in append mode.

文件 O/p:

23
24

输出/输出:

Please wait until tomorrow before entering a new value
于 2019-06-24T05:08:51.927 回答