Converting Dates and Times to Epoch Seconds
Problem
You want to convert a date and time to Epoch seconds to make it easier to do date and time arithmetic.
Solution
Use the GNU date command with the nonstandard
-d
option and a standard %s
format:
# "Now" is easy $ date '+%s' 1131172934 # Some other time needs the non-standard -d $ date -d '2005-11-05 12:00:00 +0000' '+%s' 1131192000
Discussion
If you do not have the GNU date command available, this is a harder problem to solve. Our advice is to obtain and use the GNU date command if at all possible. If that is not possible you might be able to use Perl. Here are three ways to print the time right now in Epoch seconds:
$ perl -e 'print time, qq(\n);' 1154158997 # Same as above $ perl -e 'use Time::Local; print timelocal(localtime()) . qq(\n);' 1154158997 $ perl -e 'use POSIX qw(strftime); print strftime("%s", localtime()) . qq(\n);' 1154159097
Using Perl to convert a specific day and time instead of right
now is even harder due to Perl’s date/time data structure. Years start at 1900 and
months (but not days) start at zero instead of one. The format of the
command is: timelocal
(sec, min, hour, day, month-1, year-1900)
. So
to convert 2005-11-05 06:59:49
to
Epoch seconds:
# The given time is in local time $ perl -e 'use Time::Local; printtimelocal
("49", "59", "06", "05", "10", "105") . .qq(\n);' 1131191989 # The given time is in UTC time $ perl -e 'use Time::Local; printtimegm
("49", "59", "06", "05", "10", "105") . qq(\n);' 1131173989
See Also ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.