A
A
Alikhan2021-12-01 21:18:34
Python
Alikhan, 2021-12-01 21:18:34

How to do something if it's the next day/week/month/year in Python?

You need to take some action if the next day / week / month / year has come. How can this be done in python?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2021-12-01
Mulaev @AlikhanPython

What's the problem?
To get started, get the exact date and time of the desired event. To do this, add one day\week\month\year to the current date. Then you need to return to the beginning of this next interval (day\week\month\year). In the case of a day, you need to take time off. In the case of a week, you need to discard the time and find the nearest Monday on the left - that is, subtract the number of the day of the week from the date. In the case of a month, you need to subtract from the date the number of the day of the month, in the case of a year - the number of the day of the year, respectively.
The resulting date-time of the event should now not be missed.
We just check the date-time from time to time and if it is greater than or equal to the required one, we generate an event.
You can subtract the current date-time from the date-time of the event, if this interval is less than the threshold, then sleep exactly this interval, if more, then sleep the threshold time and then repeat the check.
Leap seconds can be ignored unless you are working at intervals of less than a minute.
You can ignore the clock change if you do not work at intervals of less than a day. Otherwise, you will have to determine how the program should behave during these translations.

R
rPman, 2021-12-01
@rPman

add a day to the current date (then take the day of the month and the resulting date and compare with the current day of the month, if they are equal, then add one more second, this is to serve extra seconds), then create a new date from the day of the month and the year of the resulting variable, you will get the time of the requested event.
Further, if a simple slip is enough to complete something by this moment, subtract the current time from this variable and you will get how long you need to wait.
I do not advise using one large slip, it would be necessary to test this on boundary situations (at the time of adjusting the time on the machine from the time server), but divide the interval into several, the longer the waiting time, the longer the slip should be, and when a few seconds remain, then slips can be made short (the closer to the right moment, the shorter the wait, this will determine the response error)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question