Extraits de timestamp Unix en Perl

Exemples Perl pour obtenir le timestamp Unix actuel avec time(), formater des dates avec POSIX::strftime() et reconvertir des dates de calendrier en secondes epoch avec Time::Local.

Perl timestamp basics

Perl's built-in time() function returns the current Unix timestamp as an integer number of seconds since the epoch. The localtime() and gmtime() built-ins convert a timestamp to a list of calendar values (second, minute, hour, day, month, year, weekday, yearday, DST flag). The month from gmtime/localtime is 0-indexed (0 = January) and the year is years since 1900.

Formatting and parsing

The POSIX module ships with all standard Perl installations and provides strftime(), which formats a timestamp with the same format codes as C. For sub-second precision, Time::HiRes (also in core since Perl 5.8) overrides time() and sleep() to accept floating-point values. Time::Piece (core since Perl 5.10) adds object-oriented parsing via strptime().

Perl production notes

Perl's time() returns a native integer, so it is not subject to the Year 2038 overflow on 64-bit Perl builds. On 32-bit Perl builds, time_t is still 32-bit; check $Config{ivsize} from the Config module. Use timegm() from Time::Local when building UTC timestamps from calendar components, not timelocal(), which interprets arguments as local time.

  • Time::HiRes, POSIX, and Time::Local are all core modules and need no installation
  • The month argument to timegm() and timelocal() is 0-indexed: pass 10 for November
  • The year argument is years since 1900: pass 123 for 2023
  • Use Time::Piece->strptime for parsing arbitrary date strings instead of manual regex splitting

Frequently checked Perl details

Why does localtime() return a list instead of a string?
In list context, localtime($ts) returns (sec, min, hour, mday, mon, year, wday, yday, isdst). In scalar context it returns a ctime-style string. Use POSIX::strftime to produce a custom formatted string from the list.
How do I get sub-second timestamps in Perl?
Use Time::HiRes: 'use Time::HiRes qw(time); my $ms = int(time() * 1000);'. The module is a core Perl module so no CPAN install is needed.