在Python中获取两个日期之间的日期时间范围?

问题描述 投票:0回答:1

我已经实现了下面的代码来获取日期范围-

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)

它给出以下输出 -

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

我想每天以两小时为间隔返回此日期范围- 预期输出 -

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....

如有任何帮助,我们将不胜感激。

python python-3.x datetime date-range
1个回答
0
投票

认为这就是您正在寻找的:

from datetime import datetime, timedelta

def dates(start, end):
    def normalise(d):
        return datetime(d.year, d.month, d.day)
    _start = normalise(start)
    _end = normalise(end)
    while _start < _end:
        yield _start
        _start += timedelta(hours=2)

if __name__ == "__main__":
    today = datetime.today()
    for d in dates(today, today+timedelta(days=1)):
        print(datetime.strftime(d, "%Y-%m-%dT%H:%M:%SZ"))

这从当天开始,忽略时间部分,并继续以 2 小时的间隔生成日期时间对象。

例如,

2024-06-19T00:00:00Z
2024-06-19T02:00:00Z
2024-06-19T04:00:00Z
2024-06-19T06:00:00Z
2024-06-19T08:00:00Z
2024-06-19T10:00:00Z
2024-06-19T12:00:00Z
2024-06-19T14:00:00Z
2024-06-19T16:00:00Z
2024-06-19T18:00:00Z
2024-06-19T20:00:00Z
2024-06-19T22:00:00Z
© www.soinside.com 2019 - 2024. All rights reserved.