Reputation: 117
assume I have two dates, 2010-01-01 and 2018-12-30, I want to take the first day of every month like 2010-01-01, 2010-02-01,2010-03-01......2018-12-01.Or take a date by a specific interval like take one day every 100 days. How can I achieve this function by python? Is there a library can use? Thanks for helping!
Upvotes: 0
Views: 287
Reputation: 493
In addition, I would like to offer a script for scheduling jobs, I use the 'schedule' module.
please visit the website for installation and more details: https://schedule.readthedocs.io/en/stable/
It answers the original question and allows for multiple jobs to be scheduled and even the same job scheduled at different intervals, I added some sample tasks to illustrate the functionality
datetime
module to format the datesjob()
holds the date conditions, if they are not met then it will pass
schedule
module, you can list as many jobs as you need to execute and the schedule
module offers a lot of flexibility.while True:
loop and checking the schedule.run_pending()
method at a set interval by using the time.sleep()
functionfrom datetime import datetime
import time
import schedule
# ----------------------------- date format -------------- #
now = datetime.now()
todays_year = now.strftime("%Y")
todays_month = now.strftime("%m")
todays_day = now.strftime("%d")
start_date = datetime(2019, 1, 1)
start_date_y = start_date.strftime("%Y")
start_dat_m = start_date.strftime("%m")
end_date = datetime(2019, 12, 31)
end_date_y = end_date.strftime("%Y")
end_date_m = end_date.strftime("%m")
# ----------------------------- pending functions ------- #
def job():
"""
This function will print today's date, if date conditions are met,
it could also perform other tasks, like write to a file or DB.
"""
if int(start_dat_m) < int(todays_month) < int(end_date_m) and int(todays_year) == int(start_date_y):
print(now.strftime("%Y, %m, %d"))
else:
pass
def another_job():
print('another job')
def yet_another_job():
print('yet another job')
# ----------------------------- job scheduler --------- #
# Answers question
schedule.every(100).days.do(job)
# Sample jobs
schedule.every(2).seconds.do(job)
schedule.every(5).seconds.do(another_job)
schedule.every(1).minute.do(yet_another_job)
# ----------------------------- run pending method - #
if __name__ == "__main__":
while True:
schedule.run_pending()
time.sleep(1)
Upvotes: 1
Reputation: 1752
You can use pendulum:
It is very handy to handle dates.
You can do the following to get dates by interval.
import pendulum
start = pendulum.datetime(2019, 1, 1)
end = pendulum.datetime(2019, 12, 31)
period = pendulum.period(start, end)
for date in period.range('days', 100):
print(date)
You can see more about range here:
Upvotes: 0