Convert numeric date format (YYYYMMDD; 20150101) into Year-Month

若如初见. 提交于 2020-07-03 07:27:56

问题


Can anyone of you help in converting the date from 20150101 to abbreviated form Jan-2015 ?

I tried the below method.

x = 20150101
zoo::as.yearmon(x, "%b-%y")

But I got the below error

Error in charToDate(x) : character string is not in a standard unambiguous format

Any help would be very much appreciated.


回答1:


There are two problems with the code in the question:

  1. the input format is specified as "%b-%y" but should be "%y%m"

  2. we wish to use as.yearmon.character here rather than as.yearmon.numeric so the input should be converted to "character"

Therefore, try this:

 library(zoo)
 ym <- as.yearmon(as.character(20150101), "%Y%m")

giving:

> ym
[1] "Jan 2015"

Note that "yearmon" objects are internally stored as year + fraction where fraction is 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec. Externally they are rendered as an abbreviated month followed by a space and the year as shown.

The above may be sufficient but if not to convert it to a character string with format "%b-%y" or "%b-%Y" use format:

format(ym, "%b-%y")
## [1] "Jan-15"

format(ym, "%b-%Y")
## [1] "Jan-2015"



回答2:


You can use a combination of strptime to convert the string to a date object and format to format to what you want:

date = "20150101"
format(strptime(date,format="%Y%m%d"),"%b-%Y")



回答3:


Using lubridate and zoo packages:

library(lubridate)
library(zoo)

x <- "20150101"

as.yearmon(as.Date(ymd(x)))

[1] "jan 2015"


来源:https://stackoverflow.com/questions/29168292/convert-numeric-date-format-yyyymmdd-20150101-into-year-month

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