在PostgreSQL中计算两个日期之间的工作时间 [英] Calculate working hours between 2 dates in PostgreSQL

查看:340
本文介绍了在PostgreSQL中计算两个日期之间的工作时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一种使用Postgres(PL/pgSQL)的算法,我需要计算两个时间戳之间的工作时间,并考虑到周末不工作,而其余时间仅从上午8点到下午15点进行计数

I am developing an algorithm with Postgres (PL/pgSQL) and I need to calculate the number of working hours between 2 timestamps, taking into account that weekends are not working and the rest of the days are counted only from 8am to 15pm.

示例:

  • 从12月3日下午14点到12月4日上午9点应该算上2个小时:

  • From Dec 3rd at 14pm to Dec 4th at 9am should count 2 hours:

3rd = 1, 4th = 1

  • 从12月3日下午15点到12月7日上午8点应该算上8个小时:

  • From Dec 3rd at 15pm to Dec 7th at 8am should count 8 hours:

    3rd = 0, 4th = 8, 5th = 0, 6th = 0, 7th = 0
    

  • 最好考虑小时分数.

    推荐答案

    根据您的问题 工作时间 : Mo–Fr,08 :00–15:00 .

    According to your question working hours are: Mo–Fr, 08:00–15:00.

    1小时为单位运行.分数被忽略,因此不是 precise 而是简单的:

    Operating on units of 1 hour. Fractions are ignored, therefore not precise but simple:

    SELECT count(*) AS work_hours
    FROM   generate_series (timestamp '2013-06-24 13:30'
                          , timestamp '2013-06-24 15:29' - interval '1h'
                          , interval '1h') h
    WHERE  EXTRACT(ISODOW FROM h) < 6
    AND    h::time >= '08:00'
    AND    h::time <= '14:00';

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆