编写函数计算指定格式日期时间戳差值并返回小时结果咨询
时间差值计算实现方案
注意你给出的示例格式
9/12/2021 10:41:571存在秒级字段异常,常规秒的最大值为59,推测为输入笔误,以下实现默认按「月/日/年 时:分:秒」格式(如9/12/2021 10:41:57)编写,若末尾多的1位为毫秒位,可参考注释调整解析规则。
Excel VBA 实现(适配工作表单元格场景)
- 按
Alt + F11打开VBA编辑器,插入新模块后粘贴以下代码:
Function 时间差_小时(起始时间 As String, 结束时间 As String) As Double Dim startDt As Date, endDt As Date ' 自动截断异常的多余字符,适配你给出的带多余尾部位的格式 If Len(起始时间) > 19 Then 起始时间 = Left(起始时间, 19) If Len(结束时间) > 19 Then 结束时间 = Left(结束时间, 19) startDt = CDate(起始时间) endDt = CDate(结束时间) ' 按秒计算差值后转换为小时,保留小数位 时间差_小时 = DateDiff("s", startDt, endDt) / 3600 End Function
- 回到工作表后直接调用函数即可,比如要计算A1和B1单元格的时间差,输入公式
=时间差_小时(A1,B1)就会返回小时单位的差值。需要取整可以嵌套INT、ROUND等函数使用。
Python 实现(适配批量处理单元格导出数据场景)
from datetime import datetime def calc_hour_diff(time_str1: str, time_str2: str) -> float: # 若日期为日/月/年格式,将下面fmt中的%m和%d互换即可 # 若末尾1位是毫秒,把fmt改为"%m/%d/%Y %H:%M:%S%f"即可 fmt = "%m/%d/%Y %H:%M:%S" # 截断多余尾部位 if len(time_str1) > 19: time_str1 = time_str1[:19] if len(time_str2) > 19: time_str2 = time_str2[:19] t1 = datetime.strptime(time_str1, fmt) t2 = datetime.strptime(time_str2, fmt) return (t2 - t1).total_seconds() / 3600
- 调用示例:
calc_hour_diff("9/12/2021 10:41:571", "9/13/2021 12:41:571")返回结果为26.0
内容的提问来源于stack exchange,提问作者Bala Murali
相关产品推荐
相关产品推荐

