Bootstrap FreeKB - Perl (Scripting) - epoch date and time
Perl (Scripting) - epoch date and time

Updated:   |  Perl (Scripting) articles

The time subroutine can be used to return epoch time, which is the number of seconds that have elapsed since January 1st 1970 on a Linux system.

#!/usr/bin/perl
use strict;
use warnings;

my $epoc = time();
print "$epoc \n";

 

Something like this should be returned. In this example, 1618568411 seconds have elapsed since January 1st, 1970.

1618568411

 

The datetime subroutine can 

my $current_datetime = localtime($epoc);
print "$current_datetime \n";

 

Which should return something like this.

Fri Apr 16 05:21:31 2021

 

And here is how you would adjust the epoc time. In this example, 60 seconds are subtracted from the epoc time.

my $sixty_seconds_ago_epoc = $epoc - 60;

 

Or one hour ago.

my $one_hour_ago_epoc = $epoc - 60 * 60;

 

Or one day ago.

my $one_day_ago_epoc = $epoc - 24 * 60 * 60;

 

Or one year ago.

my $one_year_ago_epoc = $epoc - 12* 24 * 60 * 60;

 

If you have a friendly formatted date, such as 2021-04-16 05:48:12, here is how you can convert the friendly formatted date to epoch time. Note that timezone -0500 is used here. Adjust accordingly for your timezone.

#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;

print Time::Piece->strptime("2021-04-16 05:48:12 -0500","%Y-%m-%d %H:%M:%S %z")->epoch;

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 9332bb in the box below so that we can be sure you are a human.