Convert a human readable date to epoch with a shell script on OpenBSD and Mac OS X

Dates can be quite challenging. Especially if you systematically want to use dates, for example to compare what date is older.

If you would like to convert this date into epoch, take these steps.

$ # The first step is to print the date.
$ echo "2009/05/25 18:34:30;"
2009/05/25 18:34:30;
$ # This step is to strip the /-es.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g'
20090525 18:34:30;
$ # This step removes the space
$ echo "2009/05/25 18:34:30;" |  sed 's%/%%g;s% %%g'
2009052518:34:30;
$ # This step removes the trailing :30;.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%'
2009052518:34
$ # This step removes the :.
$ echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%;s%:%%g'
200905251834
$ # Finally feed that output to the "date" command.
$ date -j "+%s" $(echo "2009/05/25 18:34:30;" | sed 's%/%%g;s% %%g;s%:..;%%;s%:%%g')
1243269240

On Mac OS X you'd have to use this command:

$ date -j -f date -j -f "%Y/%m/%d %T" "2009/10/15 04:58:06" +"%s"
1255575486

Comments

Brilliant idea. This is the

Brilliant idea. This is the information that I looked for this time. - Steve Wyer

GNU date can do: date

GNU date can do:

date --date="2009/05/25 18:34:30" "+%s"

But yeah, not sure about OpenBSD/Mac.

Hi Robert, You could also

Hi Robert,

You could also do:

date --date="2009/05/25 18:34:30" "+%s"

Only thing stipped out was the semicolon. Much less effort...

I'm not sure if this is only GNU date though, but it works on Ubuntu and old red hat.

Thanks for the cool howtos.

Hi Robert, i had a slightly

Hi Robert,

i had a slightly different problem .... mylog looks like :

1249571239.862 18611 10.126.188.170 TCP_MISS/304 251 GET http://meinit/someurel - DEFAULT_PARENT/127.0.0.1 -

Which i had to hack around to a readable format.

{{{
#!/bin/sh -x
cat access.log* | gawk '{
split(substr($0,index($0," http://")+8),a,"/")
# Print out Month Webaddress
printf "%s %s\n",strftime("%b",$1),a[1]
# Print out Date(year-month-day) Webaddres
printf "%s %s\n",strftime("%Y-%m-%d",$1),a[1]
}'

About Consultancy Articles Contact




References Red Hat Certified Architect By Robert de Bock Robert de Bock
Curriculum Vitae By Fred Clausen +31 6 14 39 58 72
By Nelson Manning [email protected]