I'm using strptime
to extract date and the result is a wrong year
Where is the error in the below code:
strptime('8/29/2013 14:13', "%m/%d/%y")
[1] "2020-08-29 PDT"
What are the other ways to extract date and time as separate columns.
The data I have is in this format - 8/29/2013 14:13
I want to split this into two columns, one is 8/29/2013
and the other is 14:13
.
You have a four digit year so you need to use %Y
Do you really want data and time in separate columns? It usually much easier to deal with a single date-time object.
Here's one possibility to separate time and date from the string.
For convenience, we could first convert the string into a POSIX object:
Then we can use
as.Date()
to extract the date from this object and useformat()
to display it in the desired format:To store the time separately we can use, e.g., the
strftime()
function:The last function (
strftime()
) is not vectorized, which means that if we are dealing with a vectordatetime
containing several character strings with date and time in the format as described in the OP, it should be wrapped into a loop likesapply()
to extract the time from each string.Example
Hope this helps.