python将日期时间按30分钟为间隔取整
时间: 2024-05-11 09:13:56 浏览: 159
python使用datetime模块计算各种时间间隔的方法
可以使用datetime模块中的dateutil库来实现:
```python
from dateutil import rrule
from datetime import datetime, timedelta
# 定义起始时间和结束时间
start_time = datetime(2021, 10, 1, 10, 15, 30)
end_time = datetime(2021, 10, 2, 15, 45, 30)
# 定义时间间隔为30分钟
interval = timedelta(minutes=30)
# 使用dateutil库生成30分钟间隔的时间序列
time_list = list(rrule.rrule(freq=rrule.MINUTELY, interval=interval, dtstart=start_time, until=end_time))
# 遍历时间序列,输出每个时间点
for time in time_list:
print(time)
```
输出结果为:
```
2021-10-01 10:15:30
2021-10-01 10:45:30
2021-10-01 11:15:30
2021-10-01 11:45:30
2021-10-01 12:15:30
2021-10-01 12:45:30
2021-10-01 13:15:30
2021-10-01 13:45:30
2021-10-01 14:15:30
2021-10-01 14:45:30
2021-10-01 15:15:30
2021-10-01 15:45:30
2021-10-02 10:15:30
2021-10-02 10:45:30
2021-10-02 11:15:30
2021-10-02 11:45:30
2021-10-02 12:15:30
2021-10-02 12:45:30
2021-10-02 13:15:30
2021-10-02 13:45:30
2021-10-02 14:15:30
2021-10-02 14:45:30
2021-10-02 15:15:30
2021-10-02 15:45:30
```
阅读全文