The diff
command returns the differences between dates in a vector of dates in the R date format. I'd like to control the units that are returned, but it seems like they are automatically determined, with no way to control it w/ an argument. Here's an example:
> t = Sys.time()
> diff(c(t, t + 1))
Time difference of 1 secs
And yet:
> diff(c(t, t+10000))
Time difference of 1.157407 days
The "time delta" object has a units attribute, but it seems silly to write a bunch of conditionals to coerce everything into days, seconds etc.
timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.
Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.
Subtract the date2 from date1 To get the difference between two dates, subtract date2 from date1. A result is a timedelta object. The timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.
For example, the %H:%M:%S format codes are for hours, minutes, and seconds. To get the difference between two-time, subtract time1 from time2.
I'm not sure what you mean by "a bunch of conditionals," just change the units manually.
> t = Sys.time()
> a <- diff(c(t,t+1))
> b <- diff(c(t, t+10000))
> units(a) <- "mins"
> units(b) <- "mins"
> a
Time difference of 0.01666667 mins
> b
Time difference of 166.6667 mins
See ?difftime
. If you only need to use diff
to get the difference between two times (rather than a longer vector), then, as Dirk suggests, use the difftime
function with the units
parameter.
A POSIXct
type (which you created by calling Sys.time()
) always use fractional seconds since the epoch.
The difftime()
functions merely formats this differently for your reading pleasure. If you actually specify the format, you get what you specified:
R> difftime(t+ 10000,t,unit="secs")
Time difference of 10000 secs
R> difftime(t+ 10000,t,unit="days")
Time difference of 0.115741 days
R>
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