Convert Unix timestamp to Date-time format

Working with log files in linux/unix, you’ll inevitably come across the weirdness of a unix timestamp. It’s not intuitive working with the number of seconds since Jan 1 1970, so I rolled a little conversion utility in bash, called “utime2ymd”.

UPDATE #2:
This is unbelievably easy using GNU date, apparently. See the comments…

UPDATE: Slim, elegant version:

#!/bin/sh  
echo $1 | awk '
 {printf("%s", strftime("%Y.%m.%d ",$1));  
  printf("%s", strftime("%H:%M:%S \n",$1));
 }'  

ORGINAL oversized, but robust version (allows different timezones):

#!/bin/sh
USAGE="Usage: utime2ymd  [local|gmt]
Convert 10-digit Unix timestamp to yyyymmdd.hhmmss format
Use local time zone (default) or UTC/GMT"
[ $1 ] || { echo -e $USAGE; exit 1 ; }
unixtime=`echo $1|cut -c -10`
if [ $2 ]
then qual2=`echo $2|awk '{print tolower($1)}'`
    if [ "$qual2" = "gmt" ]
    then thetime=`perl -e "print scalar(gmtime($unixtime))"`
    fi
else
    qual2="local"
    thetime=`perl -e "print scalar(localtime($unixtime))"`
fi 

YYYYMM=`echo $thetime | awk '{print $5 $2}' \
    | sed 's/Jan/01/;s/Feb/02/;s/Mar/03/;s/Apr/04/;s/May/05/;s/Jun/06/;
           s/Jul/07/;s/Aug/08/;s/Sep/09/;s/Oct/10/;s/Nov/11/;s/Dec/12/'`

DD=`echo $thetime | awk '{printf("%02d",$3)}'`
hhmmss=`echo $thetime | awk '{print $4}' | sed 's/://g'`
echo "$YYYYMM$DD.$hhmmss $qual2"

NOTE: There’s a similar command-line tool for the Windows environment, called ‘timetool‘. Wonder if I should write a linux version??

Advertisements

4 thoughts on “Convert Unix timestamp to Date-time format

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s