python有一组csv数据计算每天不同时间段订单数量分布,给出代码实例
时间: 2024-02-13 10:07:22 浏览: 44
好的,以下是一个使用Python处理CSV数据并计算每天不同时间段订单数量分布的代码示例:
```python
import csv
from datetime import datetime, timedelta
# 读取CSV文件
with open('orders.csv', newline='', encoding='utf-8') as csv_file:
reader = csv.reader(csv_file)
# 跳过标题行
next(reader)
# 初始化时间段划分方式
start_time = datetime.strptime('00:00:00', '%H:%M:%S')
end_time = datetime.strptime('23:59:59', '%H:%M:%S')
time_interval = timedelta(hours=1) # 按小时划分
# 初始化订单数量统计字典
order_count = {}
# 遍历每一行数据
for row in reader:
order_time = datetime.strptime(row[1], '%Y-%m-%d %H:%M:%S') # 解析订单时间
order_date = order_time.date() # 获取订单日期
# 初始化订单数量统计字典中该日期的统计结果
if order_date not in order_count:
order_count[order_date] = {}
current_time = start_time
while current_time <= end_time:
order_count[order_date][current_time] = 0
current_time += time_interval
# 统计该订单所属时间段的订单数量
order_hour = order_time.replace(minute=0, second=0, microsecond=0)
order_count[order_date][order_hour] += 1
# 输出结果
for order_date, count_dict in order_count.items():
print(order_date.strftime('%Y-%m-%d'))
for current_time, count in count_dict.items():
print(current_time.strftime('%H:%M:%S'), count)
```
其中,假设CSV文件中的订单数据格式为:
```
order_id,order_time,product_id,product_name,quantity
1,2021-01-01 12:01:23,1001,Product A,2
2,2021-01-01 13:45:12,1002,Product B,1
3,2021-01-02 09:23:00,1001,Product A,3
4,2021-01-02 20:17:36,1003,Product C,2
...
```
代码中使用`csv`模块读取CSV文件,并按照日期和时间排序。时间段的划分方式为按小时划分,可以根据需要进行调整。订单数量统计使用嵌套字典进行存储,以便于按日期和时间段进行访问和输出结果。最后,使用`strftime`方法将日期和时间格式化为字符串输出。