Unix Timestamp in Perl

Perl has built-in Unix timestamp support via the time() function, which returns the current epoch in seconds. The POSIX and DateTime modules provide more advanced conversion and formatting utilities.

Ad

Code Examples

Current timestamp (seconds)

my $ts = time();

The built-in time() function returns the current Unix timestamp in seconds. No imports needed — it's available in every Perl script.

Current timestamp (milliseconds)

use Time::HiRes qw(time);
my $ts_ms = int(time() * 1000);

Time::HiRes overrides the built-in time() to return a floating-point value with sub-second precision. Multiply by 1000 and truncate for milliseconds.

Convert timestamp to human-readable

use POSIX qw(strftime);
my $date = strftime('%Y-%m-%d %H:%M:%S', gmtime($ts));

strftime with gmtime formats a Unix timestamp as a UTC date string. Use localtime instead of gmtime to apply the system's local timezone.

Parse date string to timestamp

use Time::Piece;
my $t = Time::Piece->strptime('2024-06-15 12:00:00', '%Y-%m-%d %H:%M:%S');
my $ts = $t->epoch;

Time::Piece (core module since Perl 5.10) parses date strings and exposes the epoch accessor for the Unix timestamp.

Using DateTime module (CPAN)

use DateTime;
my $dt = DateTime->now(time_zone => 'UTC');
my $ts = $dt->epoch;

The DateTime CPAN module provides a full-featured OO interface. ->epoch returns the Unix timestamp in seconds.

Note

Perl's built-in time() is the simplest way to get a Unix timestamp. For scripts that need sub-second precision or complex date arithmetic, Time::HiRes and DateTime (CPAN) are the standard choices. All of these return seconds — Perl has no native millisecond epoch function.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter