R代码转换日期时间格式

时间:2018-02-15 09:22:49

标签: r date datetime dataframe

您好我有以下数据框,其中几个日期有“dd-mm-yyyy hh:mm”格式和少量“mm / dd / yyyy hh:mm”。但是我想将所有内容更改为“mm / dd / yyyy hh:mm”格式

  

下面,“02-05-2018 07:45”采用“dd-mm-yyyy hh:mm”格式。哪一个   意思是,5月2日。我需要将它转换为2月5日   “02/05/2018 07:45”这是mm / dd / yyyy hh:mm“格式

输入:

-w

输出:

 Date / Time        Object Value
 02-05-2018 07:45   30
 02-05-2018 08:00   0
 1/30/2018 22:30    65.125
 1/30/2018 22:45    0
 1/30/2018 23:00    58

2 个答案:

答案 0 :(得分:0)

如果你的日期/时间是一个角色,你可以用POSIXct格式获得所需的日期时间:

library(lubridate)
mdy_hm("02-05-2018 07:45")

或以字符格式:

library(lubridate)
as.character(mdy_hm("02-05-2018 07:45"))

答案 1 :(得分:0)

我们可以使用anytime将多种格式转换为'DateTime'对象

anytime::anytime(df1[,1])
#[1] "2018-02-05 07:45:00 IST" "2018-02-05 08:00:00 IST" "2018-01-30 22:30:00 IST" 
#[4] "2018-01-30 22:45:00 IST" "2018-01-30 23:00:00 IST"

最好保留日期时间类而不是更改为其他格式。但是,它可以随format

而改变
format(anytime::anytime(df1[,1]), "%m/%d/%Y %H:%M")
#[1] "02/05/2018 07:45" "02/05/2018 08:00" "01/30/2018 22:30" 
#[4] "01/30/2018 22:45" "01/30/2018 23:00"

数据

df1 <- structure(list(DateTime = c("02-05-2018 07:45", "02-05-2018 08:00", 
"1/30/2018 22:30", "1/30/2018 22:45", "1/30/2018 23:00"), ObjectValue = c(30, 
0, 65.125, 0, 58)), .Names = c("DateTime", "ObjectValue"),
   class =  "data.frame", row.names = c(NA, -5L))
相关问题