I am trying to convert the date as factor to date using “as.date” function in R. I have the date in the following format
2008-01-01 02:30
I tried to use the following command :
as.Date(mydata$Date, format="%y-%m-%d %h:%mm")
Can somebody help me with this ? I was able to convert the format with no hour but getting difficulty with hour included.
Thank you.
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.
POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.
To convert characters to time objects in R, use the strptime() function. To convert time objects to characters in R, use the strftime() function.
Your format string is incorrect :
R> strptime("2008-01-01 02:30", format="%Y-%m-%d %H:%M")
# [1] "2008-01-01 02:30:00"
See ?strptime
for the detailed values you can use to define a format.
Also note that as your string is in a standard format, you can also use directly as.POSIXlt
:
R> as.POSIXlt("2008-01-01 02:30")
# [1] "2008-01-01 02:30:00"
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