我有一些包含开始时间和结束时间的数据(datetime格式),我想根据更受限制的日期范围计算持续时间(以小时为单位)。但到目前为止,我还没有成功。(对python还是个业余爱好者。)
示例:John Doe从1990-01-01T00:00:00.0到2016-12-31T23:59:59.0住在Main St 123号,但我想知道他在2015年10月到12月期间在那里住了多少小时。
下面的代码将成功计算小时数,但我无法成功筛选日期时间,因此我只能获得2015年10月1日到2015年12月31日之间的小时数。from datetime import datetime
# The getValue function retrieves the datetime values from the table
time1str = getValue("START_DT_TM")
time2str = getValue("STOP_DT_TM")
# Intended date range
# periodstart = datetime.strptime("2015-10-01T00:00:00.0", '%Y-%m-%dT%H:%M:%S.%f')
# periodend = datetime.strptime("2015-12-31T23:59:59.0", '%Y-%m-%dT%H:%M:%S.%f')
time1 = datetime.strptime(time1str, '%Y-%m-%dT%H:%M:%S.%f')
time2 = datetime.strptime(time2str, '%Y-%m-%dT%H:%M:%S.%f')
timen = datetime.strptime(nowstr, '%Y-%m-%d %H:%M:%S.%f')
timef = (time2-timen).days*24
if timef > 0:
delta = timen - time1
seconds = delta.seconds/1440
days = delta.days*24
return str(days+seconds)
else:
delta = time2 - time1
seconds = delta.seconds/1440
days = delta.days*24
return str(days+seconds)