How to convert date and time from character to datetime type

hi, how do I convert this to a datetime object that saves both date and time?

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

Tried to

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

but does not return part of the time. couldn't understand how after trying strptime and lubridate. thanks.

+3
source share
2 answers

As @Richard Scriven pointed out, you should not use as.Date , because it is not a datetime class. Here are some ways:

 DateTime <- "2007-02-01 00:00:00" DateTime2 <- "02/01/2007 00:06:10" ## default format Ymd 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/YH: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 do not need to specify format= for as.POSIXct and as.POSIXlt if you have the format %Y-%m-%d %H:%M:%S In other cases, such as %m/%d/%Y %H:%M:%S , you should usually specify the format explicitly.

+4
source

If you want to specifically convert "2007-02-01 00:00:00" to a date class object, this is what you need to do. It 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 
+1
source

Source: https://habr.com/ru/post/1203100/


All Articles