[英]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.