如何去掉时间戳并将列更改为日期格式R



我有一个日期格式的数据集,如下所示。我想:

1.从日期列中去掉时间,使其成为2/06/2020或更好的2Jun2020

2。然后我想将我的列Date转换为日期格式,这样我就可以将其子集设置为

> print(df$Date)
[1] "2/06/2020 0:00"  "12/06/2020 0:00" "12/06/2020 0:00" "29/06/2020 0:00" "3/06/2020 0:00"  "25/06/2020 0:00" "25/06/2020 0:00"
[8] "25/06/2020 0:00" "26/06/2020 0:00" "18/06/2020 0:00" "3/06/2020 0:00"  "4/06/2020 0:00"  "10/06/2020 0:00" "10/06/2020 0:00"
> summary(df$Date)
Length     Class      Mode 
16749 character character 

我试过了,但它返回了所有NA's:

df$Date2 <- as.Date(df$Date, format = "%d-%m-%Y %H:%M")

这行吗:

d <- c("2/06/2020 0:00",  "12/06/2020 0:00", "12/06/2020 0:00", "29/06/2020 0:00")
as.Date(gsub('(.*)(\s\d:\d{2})','\1',d),format = '%d/%m/%Y')
[1] "2020-06-02" "2020-06-12" "2020-06-12" "2020-06-29"

如果你想要02/06/2020格式:

format(as.Date(gsub('(.*)(\s\d:\d{2})','\1',d),format = '%d/%m/%Y'),'%d/%m/%Y')
[1] "02/06/2020" "12/06/2020" "12/06/2020" "29/06/2020"

基于上一个答案:

d = "2/06/2020 0:00"
x = format(as.Date(gsub('(\s\0(\d):\0(\d){2})','\1',d),format = '%d/%m/%Y'),'%d/%m/%Y')
gsub("^0+(\d)", "\1", x)
# [1] "2/06/2020"

相关内容

  • 没有找到相关文章

最新更新