写一段python代码,要求在导入一个csv文件,可以将其中的数据在四个时间段(6:00~7:30,7:30~15:30,15:00~17:00,17:00~6:00),四个方向(东南西北)的区别下所出现的次数进行计数,
时间: 2024-09-06 07:04:33 浏览: 39
```python
import csv
from collections import defaultdict
def count_times(file_path):
time_periods = [("6:00", "7:30"), ("7:30", "15:30"), ("15:00", "17:00"), ("17:00", "24:00"), ("00:00", "6:00")]
directions = ["东", "南", "西", "北"]
count_dict = defaultdict(lambda: defaultdict(int))
with open(file_path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader) # 跳过表头
for row in reader:
time_str, direction = row[0], row[1]
hour, minute = map(int, time_str.split(':'))
if hour >= 24:
hour -= 24
time_in_minutes = hour * 60 + minute
for period_start, period_end in time_periods:
start_hour, start_minute = map(int, period_start.split(':'))
end_hour, end_minute = map(int, period_end.split(':'))
if end_hour < start_hour:
end_hour += 24
period_start_in_minutes = start_hour * 60 + start_minute
period_end_in_minutes = end_hour * 60 + end_minute
if period_start_in_minutes <= time_in_minutes < period_end_in_minutes:
count_dict[direction][f"{period_start}-{period_end}"] += 1
break
return count_dict
file_path = "your_csv_file.csv"
result = count_times(file_path)
print(result)
```
阅读全文