LearneR
LearneR

Reputation: 2561

How to convert dates in a dataframe to a Date datatype?

I've imported one date value into R:

dtime <- read.csv("dtime.csv", header=TRUE)

It's output (7th Nov, 2013) is printed as:

> dtime
              Date
1 07-11-2013 23:06

and also its class is 'factor'.

> class(dtime$Date)
[1] "factor" 

Now, I want to extract the time details (hours, minutes, seconds) from the data. So, I was trying to convert the dataframe's date value to Date type. But none of the following commands worked:

dtime <- as.Date(as.character(dtime),format="%d%m%Y")

unclass(as.POSIXct(dtime))

as.POSIXct(dtime$Date, format = "%d-%m-%Y %H:%M:%S")

How do I achieve this in R???

Upvotes: 0

Views: 145

Answers (2)

Konrad
Konrad

Reputation: 18657

I would like to contribute solution utilising lubridate :

dates <- c("07-11-2013 23:06", "08-10-2012 11:11")
dta <- data.frame(dates)
require(lubridate)
dta$properDate <- dmy_hm(dta$dates)

If needed, lubridate will enable you to conveniently specify time zones or extract additional information.

Upvotes: 0

David Arenburg
David Arenburg

Reputation: 92310

Your attempts didn't work because the format specified was wrong.

With base R there are two possible ways of solving this, with as.POSIXlt

Res <- as.POSIXlt(dtime$Date,  format = "%d-%m-%Y %H:%M")
Res$hour
Res$min

Also, for more options, see

attr(Res, "names")
## [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"   "gmtoff"

Or a bit less conveniently with as.POSIXct

Res2 <- as.POSIXct(dtime$Date,  format = "%d-%m-%Y %H:%M")
format(Res2, "%H") # returns a character vector
format(Res2, "%M") # returns a character vector

Upvotes: 4

Related Questions