ah bon
ah bon

Reputation: 10051

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:

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.

Upvotes: 0

Views: 318

Answers (1)

norie
norie

Reputation: 9857

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"

Upvotes: 2

Related Questions