日期为另一种格式:R中的时间问题

时间:2018-10-29 09:36:14

标签: r date strptime

我有这样的约会:

dates <- c("2018-09-01 00:48:30","2018-09-01 01:34:20", "2018-09-01 01:56:28", "2018-09-01 00:06:31", "2018-09-01 01:24:30", "2018-09-01 00:54:31") 

以chr格式显示。我想得到dd / mm / yy hh:mm:ss。所以我尝试了

dates_2  <-as.character(as.Date(dates, "%Y-%m-%d %H:%M:%S"), "%d/%m/%Y %H:%M:%S") 

但是结果是

c("01/09/2018 00:00:00", "01/09/2018 00:00:00", "01/09/2018 00:00:00", 
"01/09/2018 00:00:00", "01/09/2018 00:00:00", "01/09/2018 00:00:00"

hh:mm:ss没有通过的地方...为什么有任何想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

Base R的日期类型不包含时间。一种选择是使用适当的格式掩码,使用strptime首先将文本日期时间转换为POSIXlt。然后,使用strftime,再次使用所需的掩码,将其转换回输出字符串。

x <- strptime(dates, format="%Y-%m-%d %H:%M:%S")
output <- strftime(x, format="%d/%m/%Y %H:%M:%S")

[1] "01/09/2018 00:48:30" "01/09/2018 01:34:20" "01/09/2018 01:56:28"
[4] "01/09/2018 00:06:31" "01/09/2018 01:24:30" "01/09/2018 00:54:31"