Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find a date specific days/months ago using R

I obtain today’s date by using:

> today <- format(Sys.time(), "%Y-%m-%d")
> # or use `today <- format(Sys.Date())`
> today
[1] "2021-12-23"

I hope to find a date specific days/months (let’s use 60 days or 2 months as example) ago, how could I do that in R?

The equivalent code in Python would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import datetime
from dateutil.relativedelta import relativedelta

day1 = datetime.date.today() - datetime.timedelta(days=60)
day2 = datetime.date.today() - relativedelta(months=2)
print(day1)
2021-10-24
print(day2)
2021-10-23

Sincere thanks for your help at advance.

>Solution :

If you are using lubridate you can simply add subtract days/months etc. like this.

library(lubridate)

today <- format(Sys.time(), "%Y-%m-%d")

today

ymd(today) - days(60)

ymd(today) - months(2)
> today
[1] "2021-12-23"
> 
> ymd(today) - days(60)
[1] "2021-10-24"
> 
> ymd(today) - months(2)
[1] "2021-10-23"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading