[英]Take a specific date interval by python
假设我有两个日期2010-01-01和2018-12-30,我想每个月的第一天都像2010-01-01、2010-02-01、2010-03-01 .... ..2018-12-01。或者按照特定的间隔进行约会,例如每100天间隔一天。 如何通过python实现此功能? 有图书馆可以使用吗? 感谢您的帮助!
另外,我想提供一个用于调度作业的脚本,我使用“ 调度 ”模块。
请访问网站进行安装和更多详细信息: https : //schedule.readthedocs.io/en/stable/
它回答了原始问题,并允许安排多个作业,甚至可以按不同的时间间隔安排相同的作业,我添加了一些示例任务来说明功能
datetime
模块格式化日期 job()
保存日期条件,如果不满足则将pass
schedule
模块来调度作业,您可以列出所需执行的作业, schedule
模块提供了很大的灵活性。 while True:
循环,并使用time.sleep()
函数按设置的时间间隔检查schedule.run_pending()
方法。 from 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)
您可以使用摆锤:
处理日期非常方便。
您可以执行以下操作以按间隔获取日期。
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)
您可以在此处查看有关范围的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.