*nix Tip of the Day: Unix Time

Posted Sun 06 March 2011 21:43 under category tips

As the unix-savvy among you probably know, there is One True Way to tell the time: the number of seconds elapsed since midnight on January 1, 1970 +0000. It's an extremely convenient way for computers to represent the time, since it's just an integer that goes up. There's no parsing to be done, and arithmetic is just regular math. If you want a brain-numbingly-detailed overview, Wikipedia's article on unix time is, as usual, sufficient.

However, what I'd like to talk about here is converting back and forth between unix time and meatware time. I imagine that when your beard gets long and grey enough, you are actually able to think in unix timestamps. However, for those of us who have not yet reached that level, there's the traditional unix command date. (Forewarning: some of the examples I will give here may only be applicable for the date that is part of GNU Coreutils. Mea culpa.)

The simplest thing you might want to do is find out what the current time is as a unix timestamp:

% date '+%s'
1299476266

As you can see, we haven't run out of 32-bit integer space yet.

However, what about going the other way? Sure, you could write a C/perl/python/etc. program that uses some variant on `ctime(time(NULL))`, but that's cheating. There must be a builtin? Maybe something that's not really documented? Lo, there is!

% date -d @1299476266
Sun Mar  6 21:37:46 PST 2011

It's not in the man or info pages, but there it is. The trusty @-sign solves your problem.

Cheers!


Comments