Get difference between two dates in Postgresql by days, weeks, months and years

In Order to get difference between two dates in postgresql by days, weeks, months and years. We will be using abs() function along with date difference. Let’s see how to

  • Get difference between two dates in Postgresql by days with an example.
  • Get difference between two dates in Postgresql by weeks with an example.
  • Get difference between two dates in Postgresql by months with an example.
  • Get difference between two dates in Postgresql by years with an example.

The table we use is student_detail1

Get difference between two dates in Postgresql by days, weeks, months and years 1

 

Get difference between two dates in postgresql by days with an example:

Difference between two dates in postgresql can be calculated by finding difference between two dates along with absolute function as shown below

select *,abs(birthday :: date - fin_date :: date) as diff_days from student_detail1;

So the resultant table will be

Get difference between two dates in Postgresql by days, weeks, months and years 2

 

Get difference between two dates in postgresql by weeks with an example:

Difference between two dates in postgresql by weeks can be calculated by finding difference between two dates and dividing them by 7 along with absolute function as shown below

select *,abs(birthday :: date - fin_date :: date)/7 as diff_weeks from student_detail1;

So the resultant table will be

 

Get difference between two dates in Postgresql by days, weeks, months and years 4

 

Get difference between two dates in postgresql by months with an example:

Difference between two dates in postgresql by months can be can be calculated by finding difference between two dates and dividing them by 365.25/12 along with absolute function as shown below


select *,round(abs(birthday :: date - fin_date :: date)/(365.25/12),2) as diff_months from student_detail1;

So the resultant table will be

Get difference between two dates in Postgresql by days, weeks, months and years 3

 

Get difference between two dates in postgresql by year with an example:

Difference between two dates in R by year can be calculated by finding difference between two dates and dividing them by 365.25 along with absolute function as shown below


select *,round(abs(birthday :: date - fin_date :: date)/365.25,2)  as diff_year from student_detail1;

So the resultant table will be

Get difference between two dates in Postgresql by days, weeks, months and years 5

 

                                                                                                       

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.