Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split date-time column into Date and time variables

I have a 'date-time column 'Start' in the format "Y-m-d H:M:S". I want to split this column into a "Date" and a "time" column.

I have tried the following:

df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1) df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2) 

This works, however, if I use the function str(df)

# 'data.frame':   18363 obs. of  19 variables:<br> #  $ Start    : Factor w/ 67 levels "2013-09-01 08:07:41.000",..: 1 1 1 1 1 1 1 1 1 1 ... # [snip] 

So now I only need to know how to convert the time and date from factor to 'time' and 'date'.

like image 576
Jalalala Avatar asked Oct 10 '13 09:10

Jalalala


People also ask

How do I separate a timestamp from a Date and Time?

Method 1: Use SPLIT Function Since the timestamp is composed of Date and Time, we can use the SPLIT function to extract the Date to one cell and Time to another cell. Here are the steps: On cell B2, type =SPLIT(A2, “ ”). This will automatically write the date in cell B2 and the time in cell C2.


2 Answers

How about

df$Date <- as.Date(df$Start)  df$Time <- format(df$Start,"%H:%M:%S") 
like image 53
Geoffrey Absalom Avatar answered Sep 21 '22 01:09

Geoffrey Absalom


df$Date <- as.Date(df$Start) # already got this one from the answers above df$Time <- format(as.POSIXct(df$Start), format = "%H:%M:%S")  

Use as.Date to convert 'Start' to a variables of class Date. For the time variable, we first convert 'Start' to POSIXct. Then use format to extract the time component as a string.

like image 40
Jalalala Avatar answered Sep 18 '22 01:09

Jalalala