Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weeks between two dates in Postgres

Tags:

sql

postgresql

I want to calculate the number of weeks that a customer has been a customer. The goal is to compare this to the distinct number of weeks the customer has made a purchase to determine what % of weeks the customer made a purchase.

With timestamp customer.created_at what is the best way to find the number of weeks a customer has been a customer? Said differently, the difference in weeks between the current week and the week in which the customer signed up.

Calendar weeks starting Monday to be apples-to-apples with distinct calendar weeks a customer has made a purchase.

like image 992
zach Avatar asked Jun 06 '14 05:06

zach


People also ask

How do I select data between two dates in PostgreSQL?

Use the PostgreSQL AGE() function to retrieve the interval between two timestamps or dates. This function takes two arguments: the first is the end date and the second is the start date.

What is interval in PostgreSQL?

In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years. It also has additional attribute called “precision (denoted by p)” that can be used to set the level of precision in the query results.

What is epoch in PostgreSQL?

Posted on 12th October 2022. YES, you can convert EPOCH to Timestamp by merely switching to the present Timestamp in PostgreSQL DBMS. EPOCH time is nothing but the number of seconds from 00:00:00 UTC on 1 January 1970. Till date, without adding the extra leap year days, this is considered.


2 Answers

AFAIK this should work in all cases

-Your calendar week starts on Monday
-Both dates start at least from 05.01.1970 (Monday)

Postgres:

SELECT
(
extract(epoch from date_trunc('week',now()::date))
-
extract(epoch from date_trunc('week','2019-12-20'::date))
)
/604800

(where 604800 is the number of seconds in a week)

like image 124
maleckicoa Avatar answered Sep 24 '22 06:09

maleckicoa


SELECT (EXTRACT(days FROM (now() - customer.created_at)) / 7)::int;

First find the difference between current time and customer's created_at time stamp. Then you tell Postgres to give you the difference in days and then you can divide that by 7 and round it to an integer. Note that if you do not want an integer, you can cast appropriately.

like image 27
Armon Avatar answered Sep 23 '22 06:09

Armon