[RndTbl] Convert time in seconds to date in bash?

Gilbert E. Detillieux gedetil at cs.umanitoba.ca
Tue Dec 7 11:37:19 CST 2004

According to Gilles Detillieux:
> Cool.  I had to do this just last week.  After wasting half an hour
> digging through man pages and Google searches, I gave up and wrote a q&d
> C program.  It seems there ought to be a way to do this with "date -d",
> but I can't find a way to get it to take seconds since epoch as an input.

Not sure it can be done with the "date" command.

> For that matter, I can't figure out how to get it to output the date as
> such either.

According to the date(1) man page under Red Hat Linux (any version):

       %s     seconds since 00:00:00, Jan 1, 1970 (a  GNU  extension)

So, as long as you have the GNU "date" command, "date +%s" ought to do what
you want there.

> According to Sean A. Walberg:
> > Been trying to do this one for ages... Best I can come up with uses a perl 
> > one liner:
> > 
> > perl -e 'print scalar localtime 1102434671'

I've been using a small perl script called "ctime" (attached) for years now.
It's not a one-liner, like the above, but it does simple argument handling,
calling the perl ctime() function for each numeric argument (or for the
current time in the case of no arguments).  It also accepts hex strings in
addition to decimal numbers as arguements, and converts them as required.

The following shows the (slight) difference in output format between the
GNU date command and the perl ctime script, and also shows that `date +%s`
does provide a compatible numeric date format...

% date ; ctime `date +%s`
Tue Dec  7 11:35:08 CST 2004
Tue Dec  7 11:35:08 2004

Gilbert E. Detillieux		E-mail:	<gedetil at cs.umanitoba.ca>
Dept. of Computer Science	Web:	http://www.cs.umanitoba.ca/~gedetil/
University of Manitoba		Phone:	(204)474-8161
Winnipeg, MB, CANADA  R3T 2N2	Fax:	(204)474-7609
-------------- next part --------------
#!/usr/local/bin/perl -w

require 'ctime.pl';

if ($#ARGV < 0) {
	print &ctime (time);
	exit (0);

foreach (@ARGV) {
	if (m/[a-fA-FxX]/) {
		unless (m/^0[xX]/) {
			$_ = '0x' . $_;
		$_ = oct;
	print &ctime ($_);
exit (0);

More information about the Roundtable mailing list