Divide Two Difftime Objects

Divide two difftime objects

To divide by a difftime you must convert it to numeric. If, as you stated in a comment, you would like the answer to be expressed in seconds, you can specify the 'secs' units. For example:

t1/as.double(t3, units='secs')

As @JonathanLisic notes, as.double does not generally take a units parameter, and this won't work for generic time classes. It is the S3 method for difftime which takes the parameter.

Calculating time difference and splitting datetime elements into variables

You can perform numeric computation by using timedelta.

time1 = datetime.timedelta(hours=10, minutes=33,seconds=26)
time2 = datetime.timedelta(hours=17, minutes=25,seconds=39)

time_diff = time2 - time1

hour, min, sec = str(time_diff ).split(':')

print(hour, min, sec)

Python - Calculate the difference between two datetime.time objects

To calculate the difference, you have to convert the datetime.time object to a datetime.datetime object. Then when you subtract, you get a timedelta object. In order to find out how many hours the timedelta object is, you have to find the total seconds and divide it by 3600.

# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600

Cumulative time with reset

I could not replicate @Japp's comment, but you can easily do this with dplyr.

Depending on what your exact expected output is, you could stop before the summarize call:

library(dplyr)
df=read.table(text=
"id land datetime
pb1 0 '2004-04-05 01:44:00'
pb1 1 '2004-04-05 02:00:00'
pb1 1 '2004-04-06 16:00:00'
pb1 1 '2004-04-07 16:00:00'
pb2 1 '2004-04-05 18:00:00'
pb2 1 '2004-04-05 20:00:00'", header=T) %>%
mutate(datetime=as.POSIXct(datetime,format='%Y-%m-%d %H:%M:%S'))

x = df %>%
group_by(id) %>%
arrange(id, datetime) %>%
mutate(time.land=ifelse(land==0 | is.na(lag(land)) | lag(land)==0,
0,
difftime(datetime, lag(datetime), units="days"))) %>%
mutate(cumtime.land=time.land + ifelse(is.na(lag(time.land)), 0, lag(time.land)))

id land datetime time.land cumtime.land
<fct> <int> <dttm> <dbl> <dbl>
1 pb1 0 2004-04-05 01:44:00 0 0
2 pb1 1 2004-04-05 02:00:00 0 0
3 pb1 1 2004-04-06 16:00:00 1.58 1.58
4 pb1 1 2004-04-07 16:00:00 1 2.58
5 pb2 1 2004-04-05 18:00:00 0 0
6 pb2 1 2004-04-05 20:00:00 0.0833 0.0833

The key is to use the dplyr::lag() function which takes the "line just above" in the table (which implies that you have to arrange() it beforehand).

By wrapping this inside the ifelse, I'm checking that land and previous land were not 0 (and that we are not in the first line of the id, or lag(anything) will be missing).

I then just reuse the lag() function to get the cumtime.land variable.

How do I find the time difference between two datetime objects in python?

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.

Outputting difftime as HH:MM:SS:mm in R

The subject and content of the post ask for different formats so we will assume that the one in the body of the post is desired, i.e. DD:HH:MM:SS .

Assuming the input, x, must be a vector of seconds or a difftime object:

Fmt <- function(x) UseMethod("Fmt")
Fmt.difftime <- function(x) {
units(x) <- "secs"
x <- unclass(x)
NextMethod()
}
Fmt.default <- function(x) {
y <- abs(x)
sprintf("%s%02d:%02d:%02d:%02d",
ifelse(x < 0, "-", ""), # sign
y %/% 86400, # days
y %% 86400 %/% 3600, # hours
y %% 3600 %/% 60, # minutes
y %% 60 %/% 1) # seconds
}

# test
now <- Sys.time()
now100 <- now + 100

Fmt(now100 - now)
## [1] "00:00:01:40"

Fmt(now - now100)
## "-00:00:01:40"

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.



The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00



Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.

For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.



Useful docs for this answer

  • Why 1970?
  • Date object
  • Date's getTime method
  • Date's getDate method
  • Need more accuracy than just seconds?

Combining two unequal datasets to calculate proportion

I would approach in the following way. This joins the daily duration to the category duration, converts the difftime objects to numbers and divides the two.

category_duration %>%
left_join(daily_duration, by = c("user_id", "date")) %>%
mutate(cat_duration_proportion = as.numeric(cat_duration, units = "secs") / as.numeric(duration, units = "secs"))

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.



Related Topics



Leave a reply



Submit