earth is my favourite planet
life in the pedestrian lane: science, faith, ideas, politics, techArchive for May, 2009
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??
Proof that 1=2
Assume and
.
Then
QED.