-->

date functions in R return wrong year

2020-04-19 10:27发布

问题:

I am trying to convert a character field into a date field for which the options are to either use strptime function or as.Date function. Here is two reproducible examples:

strptime(c("5/13/2015"),"%m/%d/%y")
#result is  "2020-05-13 MST"

as.Date(c("5/13/2015"), format = "%m/%d/%y")
#result is "2020-05-13"

Why did the functions change the year from 2015 to 2020? If instead, I format my date string and use the as.Date function it works. Here is what I did:

as.Date(c("2015/5/13"))

and it works fine.

any thoughts?

回答1:

I would highly recommend lubridate for date conversions

library(lubridate)

mdy("5/13/2015")

# [1] "2015-05-13"


回答2:

Your date format string should use a capital "Y", which captures the full date with century, such as "2015". Lowercase "y" is used to capture the year in two digits, as when "2015" is written in shorthand as "15". In your original cases, the strptime and as.Date functions incorrectly interpret the "20" in "2015" as the 2-digit year. The corrected version:

strptime(c("5/13/2015"),"%m/%d/%Y")

"2015-05-13 EDT"


标签: r strptime