写一段python代码,要求在导入一个csv文件,可以将其中的数据在四个时间段(6:00:00~7:30:00,7:30:00~15:30:00,15:00:00~17:00:00,17:00:00~6:00:00),四个方向(东南西北)的区别下所出现的次数进行计数。
时间: 2024-09-06 12:04:34 浏览: 32
```python
import csv
from datetime import datetime, timedelta
def count_occurrences(file_path):
with open(file_path, 'r') as csvfile:
reader = csv.reader(csvfile)
next(reader) # 跳过表头
# 初始化计数器
counts = {
"6:00:00-7:30:00": {"东": 0, "南": 0, "西": 0, "北": 0},
"7:30:00-15:30:00": {"东": 0, "南": 0, "西": 0, "北": 0},
"15:00:00-17:00:00": {"东": 0, "南": 0, "西": 0, "北": 0},
"17:00:00-6:00:00": {"东": 0, "南": 0, "西": 0, "北": 0}
}
for row in reader:
time_str = row[0] # 假设时间在第一列
direction = row[1] # 假设方向在第二列
# 将时间字符串转换为datetime对象
time_obj = datetime.strptime(time_str, '%H:%M:%S')
# 根据时间段和方向进行计数
if time_obj >= datetime.strptime("6:00:00", '%H:%M:%S') and time_obj < datetime.strptime("7:30:00", '%H:%M:%S'):
counts["6:00:00-7:30:00"][direction] += 1
elif time_obj >= datetime.strptime("7:30:00", '%H:%M:%S') and time_obj < datetime.strptime("15:30:00", '%H:%M:%S'):
counts["7:30:00-15:30:00"][direction] += 1
elif time_obj >= datetime.strptime("15:00:00", '%H:%M:%S') and time_obj < datetime.strptime("17:00:00", '%H:%M:%S'):
counts["15:00:00-17:00:00"][direction] += 1
else:
counts["17:00:00-6:00:00"][direction] += 1
return counts
# 使用示例
file_path = "your_csv_file.csv"
result = count_occurrences(file_path)
print(result)
```
阅读全文