R, strptime(), %b, trying to convert character to date format

谁说我不能喝 提交于 2019-12-22 12:48:15

问题


Hi i have some troubles concerning the strptime() function, i have character data like:

data2[,1]

24-feb-15
26-ene-15
29-dic-14

i try to use srtptime() :

strptime(data2[,1], "%d-%b-%y")

but unfortunately it only works for 24-feb-15, i guess its because the other months are spanish abbreviated, so R doesn't recognize them, i have a lot of observations so i want to find a way to do it without changing manually the name of the months. Thanks for your help.

JDaniel


回答1:


strptime will recognize abbreviated names in the current locale. You can change your current locale to spanish, transform your dates, then change it back to the original setting:

#save your current locale
original_locale<-Sys.getlocale(category = "LC_TIME")

#change it to spanish
Sys.setlocale(category = "LC_TIME", locale = "es_ES.UTF-8")

#transform your dates
data<-c("24-feb-15","26-ene-15","29-dic-14")
strptime(data,format="%d-%b-%y")

#[1] "2015-02-24 GMT" "2015-01-26 GMT" "2014-12-29 GMT"

#change it back to the original setting
Sys.setlocale(category = "LC_TIME", locale = original_locale)


来源:https://stackoverflow.com/questions/28785587/r-strptime-b-trying-to-convert-character-to-date-format

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