6

In a data.frame, I have a date time stamp in the form:

head(x$time)
[1] "Thu Oct 11 22:18:02 2012" "Thu Oct 11 22:50:15 2012" "Thu Oct 11 22:54:17 2012"
[4] "Thu Oct 11 22:43:13 2012" "Thu Oct 11 22:41:18 2012" "Thu Oct 11 22:15:19 2012"

Everytime I try to convert it with as.Date, lubridate, or zoo I get NAs or Errors.

What is the way to convert this time to a readable form?

I've tried:

 Time<-strptime(x$time,format="&m/%d/%Y  %H:$M")
    x$minute<-parse_date_time(x$time)
    x$minute<-mdy(x$time)
    x$minute<-as.Date(x$time,"%m/%d/%Y %H:%M:%S")
    x$minute<-as.time(x$time)
    x$minute<-as.POSIXct(x$time,format="%H:%M")
    x$minute<-minute(x$time)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
cconnell
  • 843
  • 1
  • 10
  • 14

2 Answers2

18

What you really want is strptime(). Try something like:

strptime(x$time, "%a %b %d %H:%M:%S %Y")

As an example of the interesting things you can do with strptime(), consider the following:

thedate <- "I came to your house at 11:45 on January 21, 2012."
strptime(thedate, "I came to your house at %H:%M on %B %d, %Y.")
# [1] "2012-01-21 11:45:00"
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
0

Another option is to use lubridate::parse_date_time():

library(lubridate)
parse_date_time(x$time, "%a %b %d %H:%M:%S %Y")

Or more simply:

parse_date_time(x$time, "abdHMSY")

From the docs:

It differs from base::strptime() in two respects. First, it allows specification of the order in which the formats occur without the need to include separators and % prefix. Such a formating argument is refered to as "order". Second, it allows the user to specify several format-orders to handle heterogeneous date-time character representations.

The docs contain all the formats (the "abdHMSY" etc.) recognized by lubridate.

sbha
  • 9,802
  • 2
  • 74
  • 62