How to calculate time differences?

I am appending a datetime to a file in this format:
2016-10-20 13:45 - My App1
2016-10-20 14:00 - My App2

I do this every time the current focused window changes.

I want to be able to also write the difference with the previous line, so after the first line, every line would look like this:
2016-10-20 14:00 - My App2 (+15 min)

This previous question is useful, but I’m kind of a newbie and I don’t know how to get the last line of a file into a variable.

Assuming you have the two lines in two variables, Line1 and Line2 (if you need to, you can read the last line from the file, but easier would be to simply remember the line in a variable each time you write it to the file so you don't have to read it), then the process would be:

  • Split the lines in to their component parts.
  • Calculate the time in seconds since the epoch.
  • Calculate the difference.
  • Convert it to hours and minutes.

Each part is relatively straight forward. Use the Search Variable action to split the line apart:

Then you use the TIME function to calculate the number of seconds since 1970 in GMT.

Then you diff them:

The you convert the result to Hours:Minutes as described here:

The result is something like this.

Keyboard Maestro Actions.kmactions (3.0 KB)

2 Likes

Or like this, with pure time calculations:

Log with Time Difference.kmmacros (4.3 KB)

Output example:

1 Like

You guys are awesome, thanks!