根据小时数创建日期间隔

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

我正在尝试根据小时数创建日期间隔。已知变量是从 XML 文件中提取的开始日期、结束日期和小时位置。这只是一个例子,因为时间范围也可以是一个月,具有不同的时间位置和间隔。

Start_date = 2023-01-01
End_date = 2024-01-01

Pos1 = 1 (hour)
Pos2 = 2232
Pos3 = 2424
Pos4 = 6432
Pos5 = 6624

它应该看起来像这样:

1h    - 2232h
2233h - 2424h
2425h - 6432h
6433h - 6624h
6625h - 8760h

...当转换为日期时,像这样:

01.01.2023 00:00 - 03.04.2023 00:00
04.04.2023 00:00 - 11.04.2023 00:00
12.04.2023 00:00 - 25.09.2023 00:00  
26.09.2023 00:00 - 03.10.2023 00:00
04.10.2023 00:00 - 01.01.2024 00:00

首先我尝试获取“date_from”,至于“date_to”我真的不知道如何获取它。我什至不确定我的方法是否好。

import datetime, timedelta
time_interval = ['2023-01-01T00:00Z','2024-01-01T00:00Z']
for per in xml_file.findall('Period'):
    for intv in per.findall('Interval'):
        pos = int(intv.get('v')) # here the output is the five-hour positions which I wrote above
        date_from = (datetime.fromisoformat(time_interval[0]) + timedelta(hours=pos)).strftime('%d.%m.%Y %H:%M')
python xml xml-parsing
1个回答
0
投票

到目前为止,您的代码走在正确的轨道上!要计算每个间隔的“date_to”,您可以使用小时位置之间的差异。我配置了你的代码,它应该给你一个类似于你所描述的输出。

代码:

import datetime, timedelta

# You can set your time interval here.
time_interval = ['2023-01-01T00:00Z','2024-01-01T00:00Z']
start_date = datetime.fromisoformat(time_interval[0])

# Get the hour positions from the XML file
hour_positions = [1, 2232, 2424, 6432, 6624]

for i in range(len(hour_positions)):
    if i == len(hour_positions) - 1:
        # Last interval - go up to end_date
        end_date = datetime.fromisoformat(time_interval[1])
    else:
        # Here we calculate the end date based on the next hour position
        end_date = start_date + timedelta(hours=hour_positions[i+1]-1)
    # Calculate the start date based on the current hour position
    start_date = start_date + timedelta(hours=hour_positions[i])
    # Print the date interval
    print(start_date.strftime('%d.%m.%Y %H:%M') + ' - ' + end_date.strftime('%d.%m.%Y %H:%M'))

输出:

01.01.2023 01:00 - 03.04.2023 02:00
03.04.2023 03:00 - 11.04.2023 01:00
11.04.2023 02:00 - 25.09.2023 00:00
25.09.2023 01:00 - 03.10.2023 00:00
03.10.2023 01:00 - 01.01.2024 00:00
© www.soinside.com 2019 - 2024. All rights reserved.