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”.

This is unbelievably easy using GNU date, apparently. See the comments…

UPDATE: Slim, elegant version:

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):

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))"`
    thetime=`perl -e "print scalar(localtime($unixtime))"`

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/;

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??


3 responses to “Convert Unix timestamp to Date-time format

Leave a Reply

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

You are commenting using your 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