Today I was working on a script, and one of the subroutines needed simple seconds-based arithmetics with time. As you probably remember from my date and time in Unix scripts article, the easiest way to approach this task is to deal with the raw representation of date and time in Unix – the Unix epoch times. This post will show you how to convert standard dates into Unix epoch times in Perl.
Why would you want to convert timestamps to Unix epoch time?
Unix epoch time is an ever-growing counter which increments every second and shows the number of seconds elapsed since 00:00:00 UTC on January 1, 1970. Such numbers are pretty useless in their raw form for the tasks of confirming current time and date, but they're perfect for measuring between two points in time.
Current epoch time in Perl
First things first. If you want to confirm the current Unix epoch time in Perl, here's how you do it: just use the time() subroutine.
#!/bin/perl print "Current (epoch) time: " . time() . "\n";
Converting regular date and time into epoch time
It's equally easy to convert time into Unix epoch representation, for this you should use timegm() or localtime() subroutine from the Time::Local module.
timegm() has the following syntax:
$current = timegm($sec,$min,$hours,$day,$month,$year);
Important: While most of the parameters are self-explanatory, it is probably worth reminding that $year should be specified as a number like 109 and not 2009.
Also, the $month is not the number of a month, but a number of months since January. So, 0 will mean January itself, 1 will mean February, and 11 means December.
Here's a fully working example, showing the countdown in seconds until midnight on the New Year's Eve 2009:
#!/usr/bin/perl # use Time::Local; # $sec=59; $min=59; $hours=23; $day=31; $month=11; $year=109; # $current = time(); print "Current (epoch) time: $current\n"; # $newyear = timegm($sec,$min,$hours,$day,$month,$year); print "New Year's Eve 2009: $newyear\n"; # print "Only " .($newyear-$current) . " seconds to go\n";
When you save this script as epoch.pl and make the file executable, here's what you'll get if you run it:
# ./epoch.pl Current (epoch) time: 1234911622 New Year's Eve 2009: 1262303999 Only 27392377 seconds to go
That's it for today! Hope this little post will save you time when tacking next scripting challenge with Perl.
Roberto says
Thank you! Really useful! You save me!
Roberto says
A question: what about time zones? I don't see any parameters to choose timzone different from greenwich.
Stan says
Here is an example of what I do. It can be tweeked to meet your needs depending on what time stamp you start with and whether you want seconds added etc. etc.. epoch time will be stored in the variable $epoch_time
$date = "04/18/2017 10:20";
$date =~ /(dd)/(dd)/(dddd) (dd):(dd)/;
$epoch_time =`date -d '$3-$1-$2 $4:$5:00 +0000' '+%s' `;