import pandas as pd
import datetime as dt
import csv
import time
# datetime对象之差,计算持续时间
def cal_time(end, start):
# 结束时间转datetime对象
end = end.strftime("%H:%M:%S")
end = dt.datetime.strptime(end, "%H:%M:%S")
# 开始时间转datetime对象
start = start.strftime("%H:%M:%S")
start = dt.datetime.strptime(start, "%H:%M:%S")
duration = (end - start).seconds
return duration # 返回持续时间
# csv文件字符串时间类型转化为datetime对象
def convert_datetime(time):
if isinstance(time, str):
return dt.datetime.strptime(time, "%d/%m/%Y %H:%M:%S")
elif isinstance(time, dt.time):
# 结束时间转datetime对象
time = time.strftime("%H:%M:%S")
time = dt.datetime.strptime(time, "%H:%M:%S")
return time
elif isinstance(time, dt.timedelta): # dt.timedelta -> 秒
return time.seconds
# 读取excel表格,人工标注
def read_excel(path):
# 打开文件
workbook = pd.read_excel(path)
ACTION = ["连续变道"]
records = []
for i, row in workbook.iterrows():
# 拿到数据
duration = cal_time(row["结束时间"], row["开始时间"])
behavior = row["违规行为"]
# 提取交通行为
for action in ACTION:
if action in behavior:
# 记录行为,保存到list
start_time = convert_datetime(row["开始时间"])
# 保存记录
line = {"action": action, "start_time": start_time, "duration": duration}
records.append(line)
return records
# 读取csv文件,数据库文件
def read_csv(path):
# 打开文件
reader = pd.read_csv(path)
# 获取开始时间
start_time = reader.iloc[0]["date_time"]
start_time = convert_datetime(start_time)
# 遍历每行
datasets = []
for i, row in reader.iterrows():
# duration = cal_time(now, start_time) # 计算当前时间与开始时间之差
time = convert_datetime(row["date_time"]) # 格式化当前时间
line = {"algorithm": row["algorithm_type_name"], "datetime": time}
datasets.append(line)
return start_time, datasets
def make_statistic(records, datasets, start_data):
# 遍历records手动标注数据
start_hand = dt.datetime(1900, 1, 1)
for record in records:
start = record["start_time"]
duration = record["duration"]
action = record["action"]
# 更新时间
start = start - start_hand # 更新手工开始时间
end = start + dt.timedelta(seconds=duration) # 更新手工结束时间
for line in datasets:
algorithm = line["algorithm"]
time = line["datetime"]
time_happen = time - start_data
# 判断
if action in algorithm:
# timedelta -> 秒
start = convert_datetime(start)
end = convert_datetime(end)
time_happen = convert_datetime(time_happen)
print("-" * 20)
print(start)
print(end)
print(time_happen)
exit()
# # 判断比较
# if start < time_happen:
# print(start, "--", time_happen)
# else:
# print("bb")
if __name__ == '__main__':
# 人工标注信息
path = r"./panzhou/201_2h.264.xlsx"
records = read_excel(path)
# 数据库里的信息
path = r"./panzhou/detect_result.csv"
start_time, datasets = read_csv(path)
# 统计算法和手工标注
make_statistic(records, datasets, start_time)
【python】datetime类型转换
最新推荐文章于 2024-04-30 19:24:04 发布