Formatting a date in R without leading zeros

丶灬走出姿态 提交于 2019-11-28 07:29:34

问题


Is there a way to use the format function on a date object, specifically an object of class POSIXlt, POSIXct, or Date, with the format %Y, %m, %d such that leading zeros are stripped from each of those 3 fields?

For example, I would like format(as.Date("1998-09-02"), "%Y, %m, %d") to return 1998, 9, 2 and not 1998, 09, 02.


回答1:


Just remove the leading zeros at the end:

> gsub(" 0", " ", format(as.Date("1998-09-02"), "%Y, %m, %d"))
[1] "1998, 9, 2"

Use %e to obtain a leading space instead of a leading zero.




回答2:


I have discovered a workaround by using year, month and day function of lubridate package. With the help of glue::glue, it is easy to do it as following:

require(lubridate)
require(glue)
dt <- "1998-09-02"
glue("{year(dt)}, {month(dt)}, {day(dt)}")
# 1998, 9, 2


来源:https://stackoverflow.com/questions/25387160/formatting-a-date-in-r-without-leading-zeros

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