Perl Snippets

Perl Unix 时间戳代码片段

Perl 示例,用于用 time() 获取当前 Unix 时间戳、用 POSIX::strftime() 格式化日期,以及用 Time::Local 将日历日期转换回纪元秒。

Current Unix timestamp (seconds)
my $ts = time();
Current Unix timestamp (milliseconds)
use Time::HiRes qw(time);
my $ms = int(time() * 1000);
Format timestamp as UTC string
use POSIX qw(strftime);
my $str = strftime("%Y-%m-%d %H:%M:%S", gmtime(1700000000));
# "2023-11-15 06:13:20"
Format timestamp as local time string
use POSIX qw(strftime);
my $str = strftime("%Y-%m-%d %H:%M:%S", localtime(1700000000));
Timestamp from date components (UTC)
use Time::Local qw(timegm);
# timegm(sec, min, hour, mday, mon, year)
# mon is 0-indexed: 10 = November
my $ts = timegm(20, 13, 6, 15, 10, 2023);
Timestamp from date components (local)
use Time::Local qw(timelocal);
my $ts = timelocal(20, 13, 6, 15, 10, 2023);
Parse ISO date string to timestamp
use Time::Piece;
my $t = Time::Piece->strptime("2023-11-15T06:13:20Z", "%Y-%m-%dT%H:%M:%SZ");
my $ts = $t->epoch;

Perl 时间戳基础

Perl 内置的 time() 函数以自纪元以来的整数秒数返回当前 Unix 时间戳。内置的 localtime() 和 gmtime() 把时间戳转换为一组日历值(秒、分、时、日、月、年、星期、年内第几天、DST 标志)。gmtime/localtime 的月份从零开始(0 = 一月),年份是自 1900 年以来的年数。

格式化与解析

POSIX 模块随所有标准 Perl 安装提供,并提供 strftime(),它用与 C 相同的格式代码格式化时间戳。对于亚秒精度,Time::HiRes(自 Perl 5.8 起也在核心中)覆盖 time() 和 sleep() 以接受浮点值。Time::Piece(自 Perl 5.10 起在核心中)通过 strptime() 增加了面向对象的解析。

Perl 生产注意事项

Perl 的 time() 返回原生整数,因此在 64 位 Perl 构建上不受 2038 年溢出影响。在 32 位 Perl 构建上,time_t 仍是 32 位;检查 Config 模块中的 $Config{ivsize}。从日历分量构建 UTC 时间戳时,使用 Time::Local 的 timegm(),而非把参数解释为本地时间的 timelocal()。

  • Time::HiRes、POSIX 和 Time::Local 都是核心模块,无需安装
  • timegm() 和 timelocal() 的月份参数从零开始:十一月传 10
  • 年份参数是自 1900 年以来的年数:2023 年传 123
  • 解析任意日期字符串时,使用 Time::Piece->strptime,而非手动用正则切分

FAQ

为什么 localtime() 返回列表而不是字符串?
在列表上下文中,localtime($ts) 返回 (sec, min, hour, mday, mon, year, wday, yday, isdst)。在标量上下文中,它返回 ctime 风格的字符串。要从该列表生成自定义格式的字符串,请使用 POSIX::strftime。
在 Perl 中如何获取亚秒时间戳?
使用 Time::HiRes:'use Time::HiRes qw(time); my $ms = int(time() * 1000);'。该模块是 Perl 核心模块,因此无需从 CPAN 安装。