Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set units of difference between datetime objects

Tags:

r

time-series

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.

like image 615
John Horton Avatar asked Mar 22 '11 19:03

John Horton


People also ask

How do you find the difference between two DateTime objects in python?

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.

How can you find the difference in time between two DateTime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.

How do you find the difference between date and time?

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.

How do I get time difference between hours in Python?

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.


2 Answers

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.

like image 67
Ian Fellows Avatar answered Oct 08 '22 13:10

Ian Fellows


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> 
like image 43
Dirk Eddelbuettel Avatar answered Oct 08 '22 12:10

Dirk Eddelbuettel