0
from datetime import datetime as dt, date, timedelta
import time
startdate= dt.now()  - timedelta(days = 7)  
enddate= dt.now()  - timedelta(days = 1)
HourList=[0,3,6,9,12,15,18,21]
 for hour in HourList:
            timeFrom = int(time.mktime(dt(startdate.year, startdate.month, startdate.day, hour,0,0,1).timetuple()))   
            timeTo = int(time.mktime(dt(enddate.year, enddate.month, enddate.day, hour+2,59,59,999).timetuple()))

By above code, am able to loop through hours . Any suggestions how to loop through dates. or by total hours of n number of days.

Expected output:
    ---
first loop
timeFrom --march 01 2020 00:00:00
timeTo --march 01 2020 02:59:59
--second loop
timeFrom --march 01 2020 03:00:00
timeTo --march 01 2020 05:59:59
---third loop
timeFrom --march 01 2020 06:00:00
timeTo --march 01 2020 08:59:59
...
...
..
---lastloop
timeFrom --march 07 2020 21:00:00
timeTo --march 07 2020 23:59:59
mr_gemini
  • 53
  • 4
  • Either you can use schedular package https://stackoverflow.com/questions/373335/how-do-i-get-a-cron-like-scheduler-in-python#16786600 or just use crontab – Shashikumar KL Apr 03 '20 at 17:06

1 Answers1

1

Forget all that mktime and timetuple stuff. You can stick with an all datetime solution if you use datetime.replace()

Like this:

from datetime import datetime as dt, timedelta

now = dt.utcnow()
week_ago = now-timedelta(days=7)
startdate = week_ago.replace(hour=0,minute=0,second=0,microsecond=0)
enddate   = now.replace(hour=0,minute=0,second=0,microsecond=0)

start = startdate
while start < enddate:
    print(start)
    end =  start+timedelta(hours=2,minutes=59,seconds=59)
    print(end)
    print("---")
    start = start+timedelta(hours=3)
Dan H
  • 14,044
  • 6
  • 39
  • 32