How to make time difference in same units when subtracting POSIXct
You can use difftime
for that propose which allows you to specify the measurement units, for example
difftime(t1, t2, units = "secs")
Another way (as mentioned by @nicola and is present in the same documentation) is to take advantage of the fact that -
has a -.POSIXt
method and override the measurement units after the subtraction operation using units<-
replacement method
res <- t1 - t2
units(res) <- "secs"
Get time difference always in minutes
Instead of just subtracting one time from another, use difftime
so you can specify the unit as minutes:
start <- Sys.time()
end <- Sys.time()
difftime(end, start, units = 'mins')
#Time difference of 0.1102342 mins
Time difference from two POSIXct objects is not calculated correctly
Have you ever heard of daylight saving time?
x
#[1] "2013-03-31 01:39:42 CET"
y
#[1] "2013-03-31 03:11:24 CEST"
Look at the time zones.
Compare with this:
x = as.POSIXct('2013-03-31 01:39:42', tz="GMT")
y = as.POSIXct('2013-03-31 03:11:24', tz="GMT")
y-x
#Time difference of 1.528333 hours
How to get time differences with output having multiple units
Since you would like days, hours, minutes, seconds, we can get this result with the lubridate
package:
a<-c("2018-03-20 11:52:25 AST", "2018-03-20 12:51:25 AST", "2018-03-20 14:19:04 AST",
"2018-03-21 14:12:12 AST", "2018-03-21 12:09:22 AST", "2018-03-21 15:28:01 AST")
b<-c("2018-04-09 18:39:38 AST", "2018-06-23 19:13:14 AST", "2018-03-20 23:23:03 AST",
"2018-05-10 21:29:28 AST", "2018-03-22 03:17:23 AST", "2018-05-12 00:19:39 AST")
a = as.POSIXct(a)
b = as.POSIXct(b)
library(lubridate)
timespan = interval(ymd_hms(ab[,1]), ymd_hms(ab[,2]))
> as.period(timespan)
[1] "20d 6H 47M 13S" "3m 3d 6H 21M 49S" "9H 3M 59S" "1m 19d 7H 17M 16S"
[5] "15H 8M 1S" "1m 20d 8H 51M 38S"
If desired, we can convert months to days by specifying the formatting as follows:
> as.period(timespan, unit = "day")
[1] "20d 6H 47M 13S" "95d 6H 21M 49S" "9H 3M 59S" "50d 7H 17M 16S"
[5] "15H 8M 1S" "51d 8H 51M 38S"
How to change the units of difftime after computing the values, and not using units=xxx when performing the calculations
What is returned by difftime
is an object of class "difftime".
Other function have methods for difftime. For example, to convert to the number of hours, as a numeric:
as.numeric(difftime("2015-12-07", "2015-12-05"), units="hours")
[1] 48
Or, to get weeks:
as.numeric(difftime("2015-12-07", "2015-12-05"), units="weeks")
[1] 0.2857143
Also, you might find it useful to remember that POSIXct
objects are actually numbers! They represent the number of seconds elapsed since ‘1970-01-01 00:00.00 UTC’
, (assumes Gregorian Calendar).
As a result, it can often be convenient to think of a unit of time of fixed duration (i.e., not something like "month", which isn't constant) and perform calculations using it. E.g., once your time difference is in seconds, it's to convert to other constant (technically there is a very fine scale variation in some of these, but most applications don't require attention to these details) time units like minutes, hours, days, or weeks.
R Find time difference in seconds for YYYY-MM-DD HH:MM:SS.MMM format
Easy peasy:
R> now <- Sys.time()
R> then <- Sys.time()
R> then - now
Time difference of 5.357 secs
R> class(then - now)
[1] "difftime"
R> as.numeric(then - now)
[1] 5.357
R>
And for your data:
R> df
time2 time3
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752
2 2011-09-05 12:25:37.42 2011-09-05 12:25:01.187
3 2011-08-24 12:56:58.91 2011-08-24 12:55:13.012
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759
R> df$time2 <- strptime(df$time2, "%Y-%m-%d %H:%M:%OS")
R> df$time3 <- strptime(df$time3, "%Y-%m-%d %H:%M:%OS")
R> df
time2 time3
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752
2 2011-09-05 12:25:37.420 2011-09-05 12:25:01.187
3 2011-08-24 12:56:58.910 2011-08-24 12:55:13.012
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759
R> df$time2 - df$time3
Time differences in secs
[1] 52.781 36.233 105.898 82.963 179.938
attr(,"tzone")
[1] ""
R>
and added back as a numeric to the data frame:
R> df$dt <- as.numeric(df$time2 - df$time3)
R> df
time2 time3 dt
1 2011-09-01 23:44:52.533 2011-09-01 23:43:59.752 52.781
2 2011-09-05 12:25:37.420 2011-09-05 12:25:01.187 36.233
3 2011-08-24 12:56:58.910 2011-08-24 12:55:13.012 105.898
4 2011-10-25 07:18:14.722 2011-10-25 07:16:51.759 82.963
5 2011-10-25 07:19:51.697 2011-10-25 07:16:51.759 179.938
R>
How to add/subtract time from a POSIXlt time while keeping its class in R?
Short answer: No
Long answer:
POSIXct
and POSIXlt
objects are two specific types of the more general POSIXt
class (not in a strictly object oriented inheritance sense, but in a quasi-object oriented implementation sense). Code freely switches between these. When you add to a POSIXlt
object, the actual function used is +.POSIXt
, not one specifically for POSIXlt
. Inside this function, the argument is converted into a POSIXct
and then dealt with (added to).
Additionally, POSIXct
is the number of seconds from a specific date and time. POSIXlt
is a list of date parts (seconds, minutes, hours, day of month, month, year, day of week, day of year, DST info) so adding to that directly doesn't make any sense. Converting it to a number of seconds (POSIXct
) and adding to that does make sense.
Time difference between rows in R dplyr, different units
ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
mutate(time_diff_2 = as.numeric(Cl_Date-lag(Cl_Date), units = 'mins'))
Convert the time difference to a numeric value. You can use units
argument to make the return values consistent.
Related Topics
How to Determine If Date Is a Weekend or Not (Not Using Lubridate)
Moving Columns Within a Data.Frame() Without Retyping
R Knitr Markdown: Output Plots Within for Loop
Creating Regular 15-Minute Time-Series from Irregular Time-Series
Spearman Correlation by Group in R
Use a Variable Within a Plotmath Expression
Shiny: Passing Input$Var to Aes() in Ggplot2
How to Complete Missing Factor Levels in Data Frame
Filling Missing Dates in a Grouped Time Series - a Tidyverse-Way
Split Data Frame into Rows of Fixed Size
R: Replace Multiple Values in Multiple Columns of Dataframes with Na
Venn Diagram Proportional and Color Shading with Semi-Transparency
Adding a Company Logo to Shinydashboard Header
Error in File(File, "Rt"):Cannot Open the Connection
How to Access and Edit Rprofile
How to Convert Integer into Categorical Data in R
Update Handsontable by Editing Table And/Or Eventreactive
Replace Empty Values with Value from Other Column in a Dataframe