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'.
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.
How about
df$Date <- as.Date(df$Start) df$Time <- format(df$Start,"%H:%M:%S")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With