Home > Back-end >  How to convert a Date column currently as 01/01/00 to 01/01/2000
How to convert a Date column currently as 01/01/00 to 01/01/2000

Time:12-16

I am working a dataset which has a Date column currently stored as Character, below is the format of how the dates are:

31/12/00

01/01/01

I want to change the year part from "00" to "2000" and "01" to "2001" for the whole column and want it in date format.

How can I do it?

enter image description here

I tried doing the following way

if(y2k_clean$Date[7:8] == "00")
  replace(y2k_clean$Date, 7, "2000")

I also tried to achieve this with gsub() but could not get the result I wanted.

Thank you.

CodePudding user response:

You could first convert it to a date with the format and after that convert it to your format with %Y as 4 digit year like this:

dates <- c('31/12/00', '01/01/01')
format(as.Date(dates,format='%d/%m/%y'), "%d/%m/%Y")
#> [1] "31/12/2000" "01/01/2001"

Created on 2022-12-16 with reprex v2.0.2

CodePudding user response:

You can use format:

df <- tibble(Date = c("31/12/00", "01/01/01"))
format(as.Date(df$Date, format="%d/%m/%y"))
  • Related