how to convert date and time from character to datetime type

前端 未结 2 417
孤独总比滥情好
孤独总比滥情好 2020-12-15 21:24

hi 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

相关标签:
2条回答
  • 2020-12-15 21:44

    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
    
    0 讨论(0)
  • 2020-12-15 21:55

    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.

    0 讨论(0)
提交回复
热议问题