簡體   English   中英

通過python采取特定的日期間隔

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

您可以使用擺錘:

https://pendulum.eustace.io/docs/

處理日期非常方便。

您可以執行以下操作以按間隔獲取日期。

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)

您可以在此處查看有關范圍的更多信息:

https://pendulum.eustace.io/docs/#range

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM