You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL Server的分钟差计算查询改写为可正确执行的pandasql语句

pandasql实现两时间差平均分钟数统计方案

pandasql底层基于SQLite语法,没有SQL Server内置的DATEDIFF函数,直接对两个时间字段做减法只会返回整数天数差值,因此需要用SQLite原生时间函数实现秒级差值计算,调整后的代码如下:

import pandas as pd
from pandasql import sqldf

# 前置处理:确保时间字段为datetime格式,避免SQLite识别异常
dffact_flight_sales['booking_created_time'] = pd.to_datetime(dffact_flight_sales['booking_created_time'])
dffact_flight_sales['booking_paid_time'] = pd.to_datetime(dffact_flight_sales['booking_paid_time'])

q2 = """
select 
  payment_method,
  round(avg((julianday(booking_paid_time) - julianday(booking_created_time)) * 86400 / 60), 2) as difference_minute
from dffact_flight_sales
group by payment_method
"""
print(sqldf(q2, locals()))

逻辑说明

  • julianday()是SQLite内置时间函数,返回对应时间的儒略日数值(浮点数格式的天数,包含时分秒对应的小数部分)
  • 两个时间的儒略日差值乘以86400(一天总秒数),即可得到和SQL ServerDATEDIFF(second, booking_created_time, booking_paid_time)完全一致的秒级差值
  • 秒级差值除以60换算为分钟,通过avg()求分组平均值后,用round()保留2位小数,和原SQL的cast as decimal(20,2)输出效果一致

内容的提问来源于stack exchange,提问作者Lix Felix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:18:00