首页 > 解决方案 > 如何将 as.character("%d-%m-%Y hh:mm") 转换为 "%d-%m-%y"

问题描述

我有这些时间dd-mm-yyyy hh:mm

               date
1  14-02-2020 21:02
2  30-04-2019 10:46
3  26-01-2019 10:10
4  26-04-2018 13:38
5  13-07-2017 10:24
6  03-02-2020 13:38
7  16-09-2020 19:35
8  10-02-2020 04:46
9  08-09-2017 13:34
10 08-09-2017 13:34

我想格式化为dd-mm-yyyy. 我试过了

p %>% mutate(new = format(as.Date(times, "%d-%m-%Y hh:mm"), "%d%m%y"))

但这没有用

p <- structure(list(times = c("14-02-2020 21:02", "30-04-2019 10:46", 
"26-01-2019 10:10", "26-04-2018 13:38", "13-07-2017 10:24", "03-02-2020 13:38", 
"16-09-2020 19:35", "10-02-2020 04:46", "08-09-2017 13:34", "08-09-2017 13:34"
)), row.names = c(NA, 10L), class = "data.frame")

标签: rdataframetimedplyrlubridate

解决方案


根据您的输入, p$dates 变量采用日期和时间格式。当你用 解析它时as.Date(),排除小时/分钟/秒信号。

p %>% mutate(dmy_date = as.Date(times,  format = "%d-%m-%Y"))

              times   dmy_date
1  14-02-2020 21:02 2020-02-14
2  30-04-2019 10:46 2019-04-30
3  26-01-2019 10:10 2019-01-26
4  26-04-2018 13:38 2018-04-26
5  13-07-2017 10:24 2017-07-13
6  03-02-2020 13:38 2020-02-03
7  16-09-2020 19:35 2020-09-16
8  10-02-2020 04:46 2020-02-10
9  08-09-2017 13:34 2017-09-08
10 08-09-2017 13:34 2017-09-08

推荐阅读