splitting date and time in data frame

走远了吗. 提交于 2019-12-01 12:54:27

Updated Answer: Beginning with your example data, you can do

data$Date <- as.POSIXct(as.character(data$Date), format =  "%Y%m%d%H%M")

to change the column to a POSIX datetime value. Then, to extract the date and time into two separate columns, you can do

data$date <- as.character(as.Date(data$Date))
data$time <- format(data$Date, "%T")

This gives the following updated data frame data

   Index                Date rank amount       date     time
1  81211 2010-04-09 00:00:00   11    4.9 2010-04-09 00:00:00
2  81212 2010-04-09 01:00:00   11    4.6 2010-04-09 01:00:00
3  81213 2010-04-09 02:00:00   11    3.3 2010-04-09 02:00:00
4  81214 2010-04-09 03:00:00   11    2.7 2010-04-09 03:00:00
5  81215 2010-04-09 04:00:00   11    3.1 2010-04-09 04:00:00
6  81216 2010-04-09 05:00:00   11    3.7 2010-04-09 05:00:00
7  81217 2010-04-09 06:00:00   11    4.0 2010-04-09 06:00:00
8  81218 2010-04-09 07:00:00   11    4.2 2010-04-09 07:00:00
9  81219 2010-04-09 08:00:00   11    4.2 2010-04-09 08:00:00
10 81220 2010-04-09 09:00:00   11    4.0 2010-04-09 09:00:00

Original Answer: If you are starting with a numeric value, wrap it in as.character() then run it through as.POSIXct() to get a POSIX date-time value.

data$Date <- as.POSIXct(as.character(data$Date), format = "%Y%m%d%H%M")

As an example I will use 201001011200 as you gave.

(x <- as.POSIXct(as.character(201001011200), format = "%Y%m%d%H%M"))
# [1] "2010-01-01 12:00:00 PST"

Then to separate out the date and time you can do the following.

list(as.Date(x), format(x, "%T"))
# [[1]]
# [1] "2010-01-01"
# 
# [[2]]
# [1] "12:00:00"

That gives Date and character classed items, respectively. For a plain old character vector, just use format() twice.

c(format(x, "%m-%d-%Y"), format(x, "%T"))
# [1] "01-01-2010" "12:00:00"  

or

c(as.character(as.Date(x)), format(x, "%T"))
# [1] "2010-01-01" "12:00:00"  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!