Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert date and time from character to datetime type

Tags:

date

datetime

r

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.

like image 760
santoku Avatar asked Sep 21 '14 14:09

santoku


People also ask

How do I change a character to a date format?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.

How do I convert a character to DateTime in R?

We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.

How do I convert text to date and time in Excel?

The DATEVALUE function in Excel converts a date in the text format to a serial number that Excel recognizes as a date. So, the formula to convert a text value to date is as simple as =DATEVALUE(A1) , where A1 is a cell with a date stored as a text string.

How do you convert date to time?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


1 Answers

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.

like image 184
nrussell Avatar answered Sep 27 '22 17:09

nrussell