I want to convert a string to datetime in R.
For example, I have '20110101000' as the string. I want to convert this to datetime '2011-01-01 00:00.' Also I would like '2011-01-01 01:00' minus '2011-01-01 00:00' = 1 hr. Eventually, I would like to have a condition where if the time difference between two date times isn't equal to 1 hour
if(diff != 1){do something}
Currently, I have used as.Date which works fine for converting string to dates, but doesn't have any options for time. Also structure with POSIXt gives me a strange result.
structure('201101010000',class=c('POSIXt', 'POSIXct'))
[1] "8342-08-21 19:40:00 EDT"
I have 100,000 + files that have to run this operation. Please let me know of the most efficient solution.
You can use the Base R package.
convert the dates to POSIXcts. Look at code below.
dt1 <- c("201101010100")
dt2 <- c("201101010200")
date1 <- as.POSIXct(dt1, format="%Y%m%d%H%M")
date2 <- as.POSIXct(dt2, format="%Y%m%d%H%M")
diff <- difftime(date2, date1, units="hours")
if(diff != 1) {
print("do something")
}
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