date functions in R return wrong year

半世苍凉 提交于 2020-01-30 09:24:26

问题


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"


来源:https://stackoverflow.com/questions/59008537/date-functions-in-r-return-wrong-year

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!