Need to find the difference between two dates along with the timestamp but I need to exclude saturday and sunday in postgresql

Viewed 115

Need to find the difference in hours between two dates along with the timestamp but I need to exclude saturday and sunday. Can you please help on this.

Thanks in Advance!!

1 Answers

step-by-step demo:db<>fiddle

SELECT
    COUNT(*) * 24                                     -- 3
FROM generate_series(start, end, interval '1 day') gs -- 1
WHERE EXTRACT('isodow' FROM gs) < 6                   -- 2
  1. Generate all dates between your start and end date
  2. Asking for the isodow (Monday = 1, Sunday = 7) and remove all records with isodow value < 6
  3. COUNT the records delivers the number of remaining dates/records, multiply it by 24 to get the hours.

Edit (Question more specific in comments):

To calculate the interval with different start and end times you could do:

  1. Calculate the days from start + 1 until end - 1 (simply (end - 1) - (start + 1))
  2. If isodow of start < 6 (start is not weekend) then add the time from start to next date ((start + 1) - start)
  3. If isodow of end < 6 (end is not weekend) then add the time from end

demo:db<>fiddle

SELECT
    COUNT(*) * interval '1 day'           -- duration of days exclude start and end
        + CASE                            -- add start if not weekend
              WHEN EXTRACT('isodow' FROM start) < 6 
              THEN (start::date + 1) - start
          END
        + CASE                            -- add end if not weekend
              WHEN EXTRACT('isodow' FROM "end") < 6 
              THEN "end" - "end"::date
          END
FROM generate_series(
    start::date + 1 , 
    "end"::date - 1, 
    interval '1 day'
) gs
WHERE EXTRACT('isodow' FROM gs) < 6
GROUP BY start, "end"
Related