LearneR LearneR -4 years ago 105
R Question

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
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")


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

How do I achieve this in R???

Answer Source

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")

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download