error in getting the correct date using strptime in R

安稳与你 提交于 2019-12-02 12:38:52

You have a four digit year so you need to use %Y

strptime('8/29/2013 14:13', "%m/%d/%Y" )
[1] "2013-08-29 CEST"

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:

datetime <- '8/29/2013 14:13'
datetime.P <- as.POSIXct(datetime, format='%m/%d/%Y %H:%M')

Then we can use as.Date() to extract the date from this object and use format() to display it in the desired format:

format(as.Date(datetime.P),"%m/%d/%Y")
#[1] "08/29/2013"

To store the time separately we can use, e.g., the strftime() function:

strftime(datetime.P, '%H:%M')
#[1] "14:13"

The last function (strftime()) is not vectorized, which means that if we are dealing with a vector datetime containing several character strings with date and time in the format as described in the OP, it should be wrapped into a loop like sapply() to extract the time from each string.


Example

datetime <- c('8/29/2013 14:13', '9/15/2014 12:03')
datetime.P <- as.POSIXct(datetime, format='%m/%d/%Y %H:%M')
format(as.Date(datetime.P),"%m/%d/%Y")
#[1] "08/29/2013" "09/15/2014"
sapply(datetime.P, strftime, '%H:%M')
#[1] "14:13" "12:03"

Hope this helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!