Unix Timestamp in Perl

Perl's time() returns seconds. Time::Piece ships with core Perl and covers most needs without extra dependencies.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

my $ts = time();                      # 1710050400

use Time::HiRes qw(time);
my $ms = int(time() * 1000);          # milliseconds

Timestamp to date

use Time::Piece;

my $t = gmtime(1710050400);
print $t->strftime("%Y-%m-%d %H:%M:%S UTC"), "\n";
print $t->datetime, "\n";             # ISO 8601

my $local = localtime(1710050400);
print $local->strftime("%Y-%m-%d %H:%M:%S %Z"), "\n";

Date to timestamp

use Time::Piece;
my $t = Time::Piece->strptime("2024-03-10 06:00:00", "%Y-%m-%d %H:%M:%S");
print $t->epoch, "\n";                # 1710050400

use Time::Local;
print timegm(0, 0, 6, 10, 2, 2024), "\n";   # mon is 0-based

DateTime for time zones

use DateTime;
my $dt = DateTime->from_epoch(epoch => 1710050400, time_zone => 'Asia/Kolkata');
print $dt->strftime("%Y-%m-%d %H:%M:%S %Z"), "\n";

Pitfalls specific to Perl

  • Time::Piece overrides the core localtime and gmtime in the importing scope, which can surprise code elsewhere in the same file.
  • timelocal and timegm take a zero-based month, matching C.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in Perl?

Use the snippet in the "Current Unix timestamp" section above. Perl works in integer seconds natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in Perl?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does Perl handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways Perl makes that easy to get wrong.