I have CSV file with "date" column but it contains two different date format as the following
7/12/2015 15:28 as m/d/yyyy hh:mm
18-04-2016 18:20 as d/m/yyyy hh:mm
How can I change the format into m/d/yyyy hh: mm, So I can subtract the dates from each other?
External packages are not required if you simply have two datetime formats. Just run both formats through the parser and take the non-missing one:
x <- c("7/12/2015 15:28","18-04-2016 18:20")
pmax(
as.POSIXct(x, format="%m/%d/%Y %H:%M", tz="UTC"),
as.POSIXct(x, format="%d-%m-%Y %H:%M", tz="UTC"),
na.rm=TRUE
)
#[1] "2015-07-12 15:28:00 UTC" "2016-04-18 18:20:00 UTC"
As far as I know, there is absolutely no way to deal with ambiguous date formats automatically, so hard-coding is the way to go here probably.
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