0

我有一个函数,它被多次调用,如果在该函数中我有一个仅在日期更改时发生的情况,那么如何做到这一点。我尝试了类似下面给定代码的方法,但它每次都会更新,任何人都可以可以提供一种方法来找到如何做到这一点

from datetime import datetime,date
import pytz
itimezone = pytz.timezone("Asia/Kolkata")
x = datetime(2021, 6, 17).date()
print(x)
y=datetime.now().date()
def f(x):
    if x>y:
        x=y;
        print(x)
        #do something
for z in range(2):
    f(x)

4

2 回答 2

1

这似乎是一个XY 问题。如果您想安排一个函数在每天 00:00 运行,那么我建议您使用schedule

import schedule

def job(...):
    # does something at 00:00 every day
    ...

schedule.every().day.at('00:00').do(job)
于 2021-06-16T13:17:19.603 回答
-1

你可以尝试这样的事情:

from datetime import date, timedelta

# Initialize previous day to yesterday to make the function run
# On first invocation
previous_date = date.today() - timedelta(days=1)

def f():
    # global keyword tells the interpreter that we want to access
    # and modify the variable outside the function closure
    global previous_date
    
    # Get current date
    today = date.today()

    # Check if current date is bigger than the stored value
    if today > previous_date:
        # Update the stored value to the new date
        previous_date = today;
        print(today)
        #do something

for _ in range(2):
    f()
于 2021-06-16T13:14:49.183 回答