Epoch in Perl

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Perl.

use strict;
use warnings;
use Time::HiRes qw(time);

# Get the current time
my $now = time;
print "$now\n";

# Get seconds since the Unix epoch
my $seconds = int($now);
print "$seconds\n";

# Get milliseconds since the Unix epoch
my $milliseconds = int($now * 1000);
print "$milliseconds\n";

# Get nanoseconds since the Unix epoch
my $nanoseconds = int($now * 1_000_000_000);
print "$nanoseconds\n";

# Convert seconds back to a time object
my $time_from_seconds = localtime($seconds);
print "$time_from_seconds\n";

# Convert nanoseconds back to a time object
my $time_from_nanoseconds = localtime($nanoseconds / 1_000_000_000);
print "$time_from_nanoseconds\n";

In Perl, we use the Time::HiRes module to get high-resolution time. The time function from this module returns the current time as a floating-point number of seconds since the Unix epoch.

We can then manipulate this value to get seconds, milliseconds, or nanoseconds. To convert back to a human-readable time format, we use the localtime function.

Here’s what the output might look like:

1622555555.12345
1622555555
1622555555123
1622555555123450000
Tue Jun  1 12:32:35 2021
Tue Jun  1 12:32:35 2021

Note that the exact values will depend on when you run the script.

Next, we’ll look at another time-related task: time parsing and formatting.