Hi and thanks for reading me. Im trying to convert a character string in to a datetime format in r, but I cannot discover the way to do that, because the year is only taken the last 2 digits ("22" instead of "2022"), im not sure of how to fix It.
The character string is "23/8/22 12:45" and I tried with:
as.Date("23/8/22 12:45", format ="%m/%d/%Y" )
and
as_datetime(ymd_hm("23/8/22 12:45"), format ="%m/%d/%Y")
But it doest work. Anyone knows how I can fix it? thanks for the help
CodePudding user response:
As has been mentioned in the comments you need to use "%d/%m/%y" to correctly parse the date in your string. But, if you want datetime format (in base r this is normally done with POSIXct classes) you could use as.POSIXct("23/8/22 12:45", format = "%d/%m/%y %H:%M")
. This will make sure you keep information about the time from your string.
CodePudding user response:
as.Date
returns only the calendar date, because class Date
objects are only shown as calendar dates.
in addition to POSIXct, you can also use parse_date_time
from lubridate package:
library(lubridate)
parse_date_time("23/8/22 12:45", "dmy HM", tz="") #dmy - day, month, year HM - hour, minute
# Or the second function:
dmy_hm("23/8/22 12:45",tz=Sys.timezone())