Home > Mobile >  Find a date specific days/months ago using R
Find a date specific days/months ago using R

Time:12-23

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.

CodePudding user response:

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"
  • Related