用于在日期时间上执行基本算术的 python 脚本



我有一个这样的csv:

Category,Position,Name,Time
A,1,Tom Smith,00:45:01.23

有多个行采用相同的格式。

我正在获得类别"A"中第一名骑手的时间,并计算出高于 15% 的时间,即如果他们需要 1 分 40 秒,那么计算时间为 1 分 55 秒。然后,它将在新的 csv 中给 Cat A 中的任何人 0 分。

我有这个代码:

def convert(seconds):  # function to convert amount of seconds to a time format
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)

with open("results.csv", 'rt', encoding='UTF-8', errors='ignore') as file:  # opening the full results file
reader = csv.reader(file, skipinitialspace=True, escapechar='\')  # skipping headers
MaleCategoryList = []  # setting category as blank so a change is recognised
for row in reader:
if row[0] not in MaleCategoryList:
if row[0] == "A":
firstPlaceTime = datetime.strptime(row[3], "%H:%M:%S.%f")
timeInSecs = firstPlaceTime.second + firstPlaceTime.minute * 60 + firstPlaceTime.hour * 3600
timeDifference = timeInSecs * 1.15
MaxTime = datetime.strptime(convert(timeDifference), "%H:%M:%S")
# some code here which is not relevant i.e calculate points
if cat == "A" and datetime.strptime(row[3], "%H:%M:%S.%f") > MaxTime:
points = int(0)
position_for_file = "DQ Time-Cut"
cat = "Time Cut"
data = {'Position': position_for_file, 'Category': cat, 'Name': name, 'Club': club,
'Points': points, 'Time': time}  # dictionary of data to write to CSV

我觉得它非常混乱和低效,因为有很多 if 循环,并且它依赖于许多似乎不必要的计算。您对我如何重写/改进它有任何想法吗?

为了简化时间算术,你可以做的是将timedelta添加到游戏中。如果从字符串中减去日期部分,则可以将从字符串中解析的时间转换为 timedelta 对象(这是在 strptime 创建日期时间对象时添加的默认值(。将其乘以 0.15 得到要添加到原始日期时间对象的 15%。前任:

from datetime import datetime, timedelta
dt = datetime.strptime('00:01:40.00', "%H:%M:%S.%f")
add = (dt - datetime(*dt.timetuple()[:3]))*0.15
dt_new = dt + add
print(dt_new.time())
# 00:01:55

顺便说一下,我还建议将pandas用于您想要做的事情(只要您有非常适合表格的数据......但是我会在那里使用相同的概念(timedelta( - 所以它不会损害在纯Python中这样做的体验。

最新更新