how to convert date and time from character to datetime type

77,275

Solution 1

As @Richard Scriven pointed out, you shouldn't be using as.Date because it's not a datetime class. Here are a few different ways:

DateTime <- "2007-02-01 00:00:00"
DateTime2 <- "02/01/2007 00:06:10"
## default format Y-m-d H:M:S
> as.POSIXct(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
> as.POSIXlt(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
##
## specify format m/d/Y H:M:S
> as.POSIXct(DateTime2,format="%m/%d/%Y %H:%M:%S",tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
> as.POSIXlt(DateTime2,format="%m/%d/%Y %H:%M:%S",tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"
##
## using lubridate
library(lubridate)
> ymd_hms(DateTime,tz=Sys.timezone())
[1] "2007-02-01 EST"
> mdy_hms(DateTime2,tz=Sys.timezone())
[1] "2007-02-01 00:06:10 EST"

You don't have to specify format= for as.POSIXct and as.POSIXlt when you have the %Y-%m-%d %H:%M:%S format. In other cases, like %m/%d/%Y %H:%M:%S, you usually have to specify the format explicitly.

Solution 2

If you want to specifically convert "2007-02-01 00:00:00" to a date-class object, this is what you need to do. This is based on this question and answer

print.POSIXct <- function(x,...)print(format(x,"%Y-%m-%d %H:%M:%S"))
x <- "2007-02-01 00:00:00"
x <- as.POSIXct(x,tz=Sys.timezone())
x
Share:
77,275
santoku
Author by

santoku

Updated on July 19, 2022

Comments

  • santoku
    santoku almost 2 years

    How shall I convert this to a datetime type object which preserves both the date and the time?

    DateTime="2007-02-01 00:00:00"
    

    Tried

    as.Date(DateTime,'%Y-%m-%d %H:%M:%S') 
    

    but doesn't return the time part. I couldn't figure out how after trying strptime and lubridate.