Reputation: 121
I`m giving an input as "a <- [12/Dec/2014:05:45:10]" a is not a time-stamp so cannot use any time and date functions
Now I want the above variable to be split down into 2 parts as:- date --> 12/Dec/2014 time --> 05:45:10
Any help will be appreciated.
Upvotes: 1
Views: 3949
Reputation: 20329
Code
a <- "[12/Dec/2014:05:45:10]"
Sys.setlocale("LC_TIME", "C") # depends on your local setting
as.POSIXlt(a, format = "[%d/%b/%Y:%H:%M:%S]")
Explanation
Depending on your local setting you need to change it such that the abbreviated month names can be read. Then you can use as.POSIXlt
together with the format string to convert your string in a date.
Upvotes: 1
Reputation: 887118
You can use gsub
to create a space between the Date and Time and use that to create two columns with read.table
read.table(text=gsub('^\\[([^:]+):(.*)+\\]', '\\1 \\2', a),
sep="", col.names=c('Date', 'Time'))
# Date Time
# 1 12/Dec/2014 05:45:10
Or you can use lubridate
to convert it to a 'POSIXct' class
library(lubridate)
a1 <- dmy_hms(a)
a1
#[1] "2014-12-12 05:45:10 UTC"
If we need two columns with the specified format
d1 <- data.frame(Date= format(a1, '%d/%m/%Y'), Time=format(a1, '%H:%M:%S'))
a <- "[12/Dec/2014:05:45:10]"
Upvotes: 4