如何创建一个函数来计算时间差(以 numpy 数组的形式)



我有两个来自.csv文件的numpy数组,其中包含时间(商店的开盘和关门时间)。我必须定义一个计算打开时间持续时间的函数。我在解决这个问题时遇到了很多麻烦,并且花了几个小时尝试。

我尝试使用datetime.datetime和timedelta等。我提到的代码来自我之前问过但后来删除的问题。

def parse_time(time_string):
#This func returns the correct datetime object if the time string can be parsed
#Else it returns -1
time_obj = -1
try:
time_obj = datetime.datetime.strptime(time_string, '%H:%M:%S')
except:
pass
return time_obj
def compute_opening_duration(opening_time, closing_time):
#Parse open and close time
ot = parse_time(opening_time)
ct = parse_time(closing_time)
#If either of them is -1, return -1
print('the opening time is: %s' %opening_time)
print('the closing time is: %s' %closing_time)
if ct == -1 or ot == -1:
return -1
#Else return time difference in hours
else:
dateTimeDifference = ct - ot
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600
print('the opening duration is: %d' %dateTimeDifferenceInHours) 

这里data_dict是从.csv文件创建的字典,打开和关闭是两个分别包含打开时间和关闭时间的numpy数组。

打开时间和关闭时间采用"小时:分钟:秒"的形式。 如果打开时间或关闭时间的形式不正确,则该函数返回 -1。

例:

开馆时间:'8:30:00',闭馆时间:'16:00:00',返回7.5

开放时间:'9:00:00',闭馆时间:'16:15:00',返回 7.25

开放时间:'8:30:00',闭馆时间:"晚上",返回-1

提到的代码不会自动计算数组中所有元素的打开持续时间和compute_opening_duration()中的值 需要提到我的我,例如。('14:00:00','16:00:00') .我正在寻找一种解决方案,该函数直接从数组中获取值(时间)并将输出转换为数组。

为此,我只是遍历了打开和关闭时间的列表,并将函数的结果放入另一个数组中以返回。如果数组大小不匹配,则函数返回类似于函数的 -1。

这是代码:

def compute_hours_array(open_times, close_times):
# parameters are arrays. 
operating_hours = []
if len(open_times) == len(close_times):
for k in range(len(open_times)):
operating_hours.append(compute_opening_duration(open_times[k],close_times[k]))
return operating_hours
return -1

希望有帮助。

最新更新