python - 使用 Postgres 的 SQLAlchemy 中两个日期之间的平均天数

标签 python postgresql flask sqlalchemy flask-sqlalchemy

我正在尝试计算 2 个日期的天数差异,然后取平均值。所有示例似乎都使用 date_sub 来获取日期和时间间隔。有没有一个函数可以得到两个日期的差值,然后将其转换为天数,然后取平均值。

从 sqlalchemy.sql 导入函数,文本

尝试线

func.avg(func.date_sub(Booking.departure_date, Booking.booking_date)).label('average_lead_time')).\ 

查询

query = db.session.query(func.avg(Booking.total_including_tax).label('average_fare'),
                        func.date_part('year', Booking.query_date).label("year"),
                        func.date_part('month', Booking.query_date).label("month"),
                        func.avg(func.date_sub(Booking.departure_date, Booking.booking_date)).label('average_lead_time')).\
                        filter(Booking.client_id == client_id).\
                        filter(Booking.customer_id == customer_id).\
                        filter(Booking.booking_type == 'Air').\
                        filter(Booking.query_date is not None).\
                        filter(Booking.query_date >= filter_date_range_min).\
                        filter(Booking.query_date < filter_date_range_max).\
                        group_by('year').group_by('month').\
                        order_by('year').order_by('month')

最佳答案

我正在寻找的行只是我不需要该功能,因为我可以使用 - 符号。我需要 postgres justify_days 函数

func.avg(func.justify_days(Booking.departure_date - Booking.booking_date)).label('average_lead_time')).\

这有帮助

http://www.postgresql.org/docs/current/static/functions-datetime.html

关于python - 使用 Postgres 的 SQLAlchemy 中两个日期之间的平均天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859991/

相关文章:

python - 如何在 Python 中合并具有共同子字符串的字符串以在数据框中生成一些组

通过终端连接 Postgresql - pgadmin

sql - 我如何在 PostgreSQL 中执行 DISTINCT 和 ORDER BY?

python - 将 Python Flask 应用部署到 Google App Engine 时没有名为 'flask' 的模块

python - 无法在 View 函数中的 2 个 flask 请求之间共享变量

python - 防止 BufferedReader 关闭文件列表的文件

python - 如何从用户那里读取单个字符?

python - flask 同一页面上的多个表单

python - BeautifulSoup 刮电影标题和图像

postgresql - CREATE TABLE AS 不允许在 Postgresql 的非 volatile 函数中使用