Wednesday, August 05, 2026

[hgulalrr] subtracting times of day with units

time elapsed between:
4th day of the month 11:59:59 PM
6th day of the month 6:06:06 AM

$ units
You have: (6 day + 6 hr + 6 min + 6 s) - (4 day + 23 hr + 59 min + 59 s)
You want: day;hr;min;s
1 day + 6 hr + 6 min + 7 s

the semicolon syntax is documented in the units man page in the section entitled "UNIT LISTS: CONVERSION TO SUMS OF UNITS".

computing elapsed time requires more effort if endpoints are in different months, e.g., January 31, February 1 = January 32, February n = January (31 + n),... March 1 = February ( {28 or 29} + 1) = January (31 + {28 or 29} + 1).

incorrect if Daylight Saving Time changes within the interval; incorrect if endpoints are in different time zones; incorrect if a leap second occurs; incorrect if crossing the boundary between Gregorian and Julian calendars.

for such complicated cases, first convert each endpoint into a format which increases continuously and uniformly, then subtract, then convert with units to "day;hour;minute;second".

note well that Unix time does NOT increase uniformly: it stops at a leap second (or more precisely, it discontinuously decreases by one second).  subtracting two Unix times yields an elapsed time value that is incorrect by the number of leap seconds which occurred during the interval.

use the "right" counter instead of POSIX Unix time.  note that, as of Debian Trixie, you need to install the tzdata-legacy package to get the "right" counter value of a given date and time.

No comments :