Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: Get number of days since date

Tags:

postgresql

I have a table with information about articles. I have a published_at column that's a timestamp without time zone and want to calculate how long ago each article was published, in days.

So if it was published a week ago, I should get back 7.

Any idea how to go about?

I know Postgres has NOW() but can I just subtract and then take DAY()?

Thanks!

like image 356
anon_swe Avatar asked Aug 03 '17 14:08

anon_swe


People also ask

How do I count days between two dates in PostgreSQL?

To count the difference between dates as days in PostgreSQL or Oracle, you simply need to subtract one date from the other, e.g. arrival - departure . But in most cases, what you really want is the number of days from the first date to the second date inclusively.

Does PostgreSQL have datediff?

PostgreSQL provides a datediff function to users. The datediff means we can return the difference between two dates based on their specified interval. The datediff function plays an important role in the database management system because datediff functions as a calendar and it is very helpful to users.


1 Answers

You can subtract one date from another, the result will be the number of days between the two dates. If one of them is a timestamp, just cast it to a date:

select current_date - published_at::date
from your_table;

If you want to get those that are younger then 7 days, you can use:

select current_date - published_at::date as age_in_days
from your_table
where published_at >= current_date - 7;
like image 99
a_horse_with_no_name Avatar answered Nov 04 '22 16:11

a_horse_with_no_name