0

i have a function which as been called multiple times the problem with me if in that function i have a condition which happens only when the date changes so how to do that.I tried something like below given code but it is getting updated everytime can anyone can give a way to find how to do that

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)

  • `x` is greater than `y` so your `if` condition is always `True`. Keep in mind, you're *passing* x to the function but not changing it. – not_speshal Jun 16 '21 at 13:13
  • yes that i got to know do you know any way how to do that – Yash Bontala Jun 16 '21 at 13:16
  • 1
    side-note: `datetime.now()` gives you local time. If that is what you want: no need to set a time zone. Otherwise, use [zoneinfo](https://docs.python.org/3/library/zoneinfo.html). – FObersteiner Jun 16 '21 at 13:20
  • 1
    Does this answer your question? [How do I get a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/how-do-i-get-a-cron-like-scheduler-in-python) – FObersteiner Jun 16 '21 at 13:21

2 Answers2

1

This seems like an X Y problem. If you want to schedule a function to be run every day at 00:00, then I would recommend you use schedule:

import schedule

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

schedule.every().day.at('00:00').do(job)
Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
  • is it reliable will it not make my execution slow as it's run in an infinite loop – Yash Bontala Jun 16 '21 at 13:30
  • @YashBontala The Schedule library is reliable, and is widely used in production code. I recommend you read the docs to see if it's right for you, and how to use it in more detail: https://schedule.readthedocs.io/en/stable/ – Will Da Silva Jun 16 '21 at 13:40
-1

You can try something like this:

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()
Joac
  • 492
  • 3
  • 12
  • will it work have you checked it why did you did global previous_date i did not understand what you wrote – Yash Bontala Jun 16 '21 at 13:19
  • I added a change to make the function run on the first call, and commented the code for clarity. – Joac Jun 16 '21 at 13:29