如何在亚洲/加尔各答时区安排python作业



嗨,我已经使用下面提到的代码成功地安排了一个python作业

import schedule
import time
def job():
print("I am doing this job!")

schedule.every().monday.at("14:00").do(job)
schedule.every().tuesday.at("14:00").do(job)
schedule.every().wednesday.at("14:00").do(job)
schedule.every().thursday.at("14:00").do(job)
schedule.every().friday.at("14:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)

现在我只需要在亚洲/加尔各答时区执行时间表。我们可以用pytz库吗?

如果你绝对必须使用时间表库,并且你想使用不同的时区,那么你必须根据时间表库的时区手动指定时间。

import schedule
import time
from datetime import datetime
import pytz # you'll have to install pytz to get timezones
def job():
print("I am doing this job!")
# Create a time zone object for Asia/Kolkata
kolkata_tz = pytz.timezone('Asia/Kolkata')
# Define the desired time for the job in Kolkata time
job_time = datetime.now(kolkata_tz).replace(hour=14, minute=0, second=0, microsecond=0)
# Schedule the job for each weekday at the specified time 
schedule.every().monday.at(job_time.strftime("%H:%M")).do(job)
schedule.every().tuesday.at(job_time.strftime("%H:%M")).do(job)
schedule.every().wednesday.at(job_time.strftime("%H:%M")).do(job)
schedule.every().thursday.at(job_time.strftime("%H:%M")).do(job)
schedule.every().friday.at(job_time.strftime("%H:%M")).do(job)
while True:
schedule.run_pending()
time.sleep(1)

最新更新