seconds: CLI for quick time interval calculation

[Tweet : nvALT]

Here’s a quick script I swear I’ve written before but couldn’t find. If given a string as an argument, it converts it to seconds, and if given just a series of numbers, it converts the number to a human-readable string.

I needed this today when setting update intervals for Sparkle, and it’s something I’ve run into in the past. I usually pull up a calculator, which is annoying. There’s probably a simple Unix way to do it that I’ll hear about in the comments, which is ok, I still had fun writing it.

Since this is mostly likely to be of use to programmers, I won’t bother detailing how to turn it into an executable script. You got this.

Convert strings to seconds

Arguments are numbers followed by a timespan. It works on shorthand (w = week, day = d, hours = h, minutes = m, seconds = s), but will convert most strings to this format automatically, e.g. “2 days, 3 hours, and 30 min” is the same as “2d3h”. As long as the format is a number followed by strings that start with w, d, h, m, or s, it’ll figure it out.

$ seconds 3d2h
=> 266400
$ seconds 2 days, and 3 hours
=> 183600

Convert seconds to a human-readable string

$ seconds 266400
=> 3 days, 2 hours

Here’s the script. Do with it what you will.