python定時執行--月
阿新 • • 發佈:2018-11-23
下面的程式碼實現每個月執行:其中呼叫了一個判斷是否為最後一天的方法
import datetime import time import pymysql from isLastDayOfMonth import isLastDayMonth def doSth1(): # 連結資料庫 conn = pymysql.Connect( host='192.0.9.169', port=5507, user='writer', passwd='Apsdf', db='api_data', charset='utf8' ) cur = conn.cursor() cur.execute('''select * from table2''') conn.commit() cur.close() conn.close() # 假裝做這件事情需要一分鐘 time.sleep(60) def main(h=23 , m=0): while isLastDayMonth(datetime.datetime.now()) ==1: while True: now = datetime.datetime.now() # 到達設定時間,結束內迴圈 if now.hour == h and now.minute == m: break # 不到時間就等20秒之後再次檢測 time.sleep(20) # 做正事,一天做一次 doSth1() if __name__ == '__main__': main()
判斷是否最後一天:
import time,datetime # 當前時間 now_time = datetime.datetime.now() now_time_mk = time.mktime(now_time.timetuple()) # 當前時間戳 # 下月第一天最後一秒時間 month = now_time.month if month == 12: month = 0 def isLastDayMonth(i): first_day = datetime.datetime(now_time.year, now_time.month + 1, 1, 23, 0, 0) # print(first_day) # 上個月最後一天 up_last = first_day - datetime.timedelta(days=1) # print(up_last) # 上個月第一天第一秒 up_first_day = datetime.datetime(up_last.year, up_last.month, 1) # print(up_first_day) if i == up_last: return 1 else: return 0 def main(): isLastDayMonth(datetime.datetime.now()) if __name__ == '__main__': main()