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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With