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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With