Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date difference in years (floating point)

Tags:

date

r

I want to correct source activity based on the difference between reference and measurement date and source half life (measured in years). Say I have

ref_date <- as.Date('06/01/08',format='%d/%m/%y') 

and a column in my data.frame with the same date format, e.g.,

today <- as.Date(Sys.Date(), format='%d/%m/%y') 

I can find the number of years between these dates using the lubridate package

year(today)-year(ref_date) [1] 5 

Is there a function I can use to get a floating point answer today - ref_date = 5.2y, for example?

like image 766
moadeep Avatar asked Mar 22 '13 11:03

moadeep


People also ask

How do I get the year difference between two dates in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.


2 Answers

Yes, of course, use difftime() with an as numeric:

R> as.numeric(difftime(as.Date("2003-04-05"), as.Date("2001-01-01"),  +                      unit="weeks"))/52.25 [1] 2.2529 R>  

Note that we do have to switch to weeks scaled by 52.25 as there is a bit of ambiguity there in terms of counting years---a February 29 comes around every 4 years but not every 100th etc.

So you have to define that. difftime() handles all time units up to weeks. Months cannot be done for the same reason of the non-constant 'numerator'.

like image 161
Dirk Eddelbuettel Avatar answered Sep 30 '22 19:09

Dirk Eddelbuettel


The lubridate package contains a built-in function, time_length, which can help perform this task.

time_length(difftime(as.Date("2003-04-05"), as.Date("2001-01-01")), "years") [1] 2.257534  time_length(difftime(as.Date("2017-03-01"), as.Date("2012-03-01")),"years") [1] 5.00274 

Documentation for the lubridate package can be found here.

like image 20
Bryan F Avatar answered Sep 30 '22 20:09

Bryan F