How can I put my end date to tomorrow? Trying to schedule a program to run everyday

Viewed 79

I need this code to be run between and only during these hours 11:30 am (Current day) to 3:30 AM (The next day.)

The issue I am having with this code is: When I print the d4 and d5, it prints todays date. However, d5 should print the next day. I did some testing and changed my windows time. put starttime at 23:59:00 and endtime at 00:02:00. The scheduler ended up not starting the process.

This is the console output when I put the endtime at 00:02:00:

Console output

The code runs if the hours are within the same day. So starttime 08:30 and endtime at 09:30. How can I fix this?

Below is my json file layout

timechanges":[{
        "startTime":" 23:58:00",
        "endTime":" 00:01:00"
import schedule
import time 
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import date

class myproject():
    def __init__(self):

        today = date.today()
        with open(root / 'time.json', "r") as rf:
            decoded_data = json.load(rf)
            for p in decoded_data['timechanges']:
                startTime=p['startTime'] 
                endTime=p['endTime'] 

        d3 = today.strftime("%Y-%m-%d")
        print("d3 =", d3)
        d4 = d3+startTime
        print("Start time:", d4)
        d5 = d3+endTime
        print("End time:",d5)
        sched = BlockingScheduler()
        
        job=sched.add_job(self.process, 'interval', minutes=2, start_date=d4, end_date=d5)
        sched.start()
        job.remove()
        sched.shutdown()
        print("Scheduler shut down")

    def process(self):
        print("running")
1 Answers

What about working with datetime and timedelta instead of strings? You could add a day to endTime's date if starttime > endTime. Ex:

from datetime import datetime, timedelta

today = datetime.now()
startTime = "23:58:00"
endTime = "00:01:00"

startTime = datetime.combine(today.date(), datetime.strptime(startTime, "%H:%M:%S").time())
endTime = datetime.combine(today.date(), datetime.strptime(endTime, "%H:%M:%S").time())

if endTime < startTime:
    endTime += timedelta(1) # add a day

print("today's date =", today.date())
# today's date = 2021-01-05

print("Start date/time:", startTime.isoformat(" "))
# Start date/time: 2021-01-05 23:58:00

print("End date/time:", endTime.isoformat(" "))
# End date/time: 2021-01-06 00:01:00
Related