Home > front end >  change years in datetime array to current year
change years in datetime array to current year

Time:09-17

How can I change year component to 2021 in all datetime values using lubridate?

library(lubridate)
library(dplyr)

time <- ymd_hms(c("2018-01-05 12:00:15", "2018-01-01 02:00:15", "2018-02-25 12:00:15", 
                  "2018-04-15 12:00:15", "2020-10-15 12:00:15", "2019-10-20 12:00:15",
                  "2019-11-15 12:01:15", "2018-11-02 11:00:15", "2018-07-09 02:00:15",
                  "2020-10-02 11:00:15", "2020-01-29 12:00:15", "2019-03-15 12:00:15")
                )

tbl <- tibble(time)

CodePudding user response:

year(tbl$time) = 2021


> tbl
# A tibble: 12 × 1
   time               
   <dttm>             
 1 2021-01-05 12:00:15
 2 2021-01-01 02:00:15
 3 2021-02-25 12:00:15
 4 2021-04-15 12:00:15
 5 2021-10-15 12:00:15
 6 2021-10-20 12:00:15
 7 2021-11-15 12:01:15
 8 2021-11-02 11:00:15
 9 2021-07-09 02:00:15
10 2021-10-02 11:00:15
11 2021-01-29 12:00:15
12 2021-03-15 12:00:15
  • Related