pythonpython-3.xdatetimedate-range

Get the datetime range between two dates


I have implemented below code to get date range -

from datetime import timedelta, date,datetime

def daterange(date1, date2):
    # Iterate over the range of days between date1 and date2
    for n in range(int((date2 - date1).days) + 1):
        # Yield each date within the range
        yield date1 + timedelta(n)

##Logic to fetch data in daterange
current_date = datetime.today()
# day = int(current_date.strftime('%d'))
day = 19
year = int(current_date.strftime('%Y'))
month = int(current_date.strftime('%m'))

if str(day) == '19':
    # Define the start date
    start_dt = date(year, month, 18)
    # Define the end date
    end_dt = date(year, month, day)
elif str(day) == '28' or str(day) == '30' or str(day) == '31' or str(day) == '29':
    # Define the start date
    start_dt = date(year, month, 16)
    # Define the end date
    end_dt = date(year, month, day)

# Iterate over the range of dates generated by the daterange function
for dt in daterange(start_dt, end_dt):
    # date in the format YYYY-MM-DD
    dated = dt.strftime("%Y-%m-%d")
    startdate = str(dated) + 'T00:00:00Z'
    enddate = str(dated) + 'T03:00:00Z'
    print(startdate)
    print(enddate)

It gives below output -

2024-06-18
2024-06-18T00:00:00Z
2024-06-18T03:00:00Z
2024-06-19
2024-06-19T00:00:00Z
2024-06-19T03:00:00Z

I want to return this date range in interval of two hours for each day- Expected output -

2024-06-18T00:00:00Z
2024-06-18T02:00:00Z
2024-06-18T02:00:00Z
2024-06-18T04:00:00Z
2024-06-18T04:00:00Z
2024-06-18T06:00:00Z
2024-06-18T06:00:00Z
2024-06-18T08:00:00Z......
2024-06-18T22:00:00Z
2024-06-19T00:00:00Z......
2024-06-19T00:00:00Z
2024-06-19T02:00:00Z....

Any help would be appreciated.


Solution

  • You can use the pandas function pd.date_range() with which you can specify the frequency, like this:

    pd.date_range("2024-06-18 00:00", "2024-06-19 02:00", freq="2h")
    

    This returns a DatetimeIndex object that contains dates in Timestamp objects, but if you need to, you can use to_pydatetime() method to get the dates in datetime objects

    pd.date_range("2024-06-18 00:00", "2024-06-19 02:00", freq="2h").to_pydatetime()