Python 每天最多打印一封邮件

Python 每天最多打印一封邮件,python,time,Python,Time,我有以下代码 如果条件允许,我想打印一条消息,每天最多打印一条消息(或其他时间间隔) 时间间隔=86400 def print_message(): ... 如果名称=“\uuuuu main\uuuuuuuu”: 尽管如此: 如果未打印且(t=t_min): 如果(上次消息打印时间间隔超过一个时间间隔):# 打印消息() ... 时间。睡眠(900) 我需要在代码中记住最后一条消息是何时打印的,距离现在不超过一天。如果超过I天,则条件#已满。对此,我将使用datetime: import d

我有以下代码

如果条件允许,我想打印一条消息,每天最多打印一条消息(或其他时间间隔)

时间间隔=86400
def print_message():
...
如果名称=“\uuuuu main\uuuuuuuu”:
尽管如此:
如果未打印且(t=t_min):
如果(上次消息打印时间间隔超过一个时间间隔):#
打印消息()
...
时间。睡眠(900)

我需要在代码中记住最后一条消息是何时打印的,距离现在不超过一天。如果超过I天,则条件#已满。

对此,我将使用
datetime

import datetime

...

# interval is one day
INTERVAL = datetime.timedelta(days=1)
# set the 'last_printed' to one day ago, initially
last_printed = datetime.datetime.now() - INTERVAL

def do_thing_at_most_once_per_day():
    global last_printed
    # check the current time and see if it's been at least a day
    if datetime.datetime.now() - last_printed > INTERVAL:
        # at least one day has passed
        print_message()
        last_printed = datetime.datetime.now()
    else:
        # nothing happens
        pass
请记住,由于这一切都将发生在单个程序中,因此必须保持该程序的运行才能使其全部正常工作。如果您需要记住程序不同运行之间最后打印的时间,那么您可能需要将时间存储在文件中,并使用诸如
datetime.datetime.strtime()
datetime.datetime.strftime()
之类的方法来读取和写入这些时间


.

不仅仅是重新发布。但是,当我将间隔更改为20秒时,它是否有效?这是因为我在代码中使用了86400(天)秒。您可以将
INTERVAL
更改为您想要的任何值。20秒就是datetime.timedelta(秒=20)谢谢,我会试试看。
import datetime

...

# interval is one day
INTERVAL = datetime.timedelta(days=1)
# set the 'last_printed' to one day ago, initially
last_printed = datetime.datetime.now() - INTERVAL

def do_thing_at_most_once_per_day():
    global last_printed
    # check the current time and see if it's been at least a day
    if datetime.datetime.now() - last_printed > INTERVAL:
        # at least one day has passed
        print_message()
        last_printed = datetime.datetime.now()
    else:
        # nothing happens
        pass