Perl - 将字符串转换为日期时间
Perl - convert string to datetime
我正在编写一个从日志文件中获取数据的脚本。日志文件包含特定格式的日期字符串:
20190626-102908.616319
通过我的代码解析后,我希望日期采用另一种格式:
2019-06-26-10:29:08
我用过 DateTime::Format::Strptime
,效果很好。
但是,要求是使用另一种方式,因为将使用脚本的系统不允许安装新模块(是的,我不能安装额外的 Perl 模块)。
我唯一能合作的是Date::Parse
或Date::Format
,但我不能让它合作。
与Date::Parse
:
my $time2 = str2time($chunks[0]);
我只得到空输出。
呼叫 Date::Format
:
my $time2 = time2str("%Y-%m-%d-%H:%M:%S\n", $chunks[0]);
只给出 1970-01-01-00:00:00
.
有人能给我指出正确的方向吗?
给定 20190626-102908.616319 作为 $string
的内容
my ($date,$time) = split /-/, $string; # Separate time from date
$time = int $time; # Drop decimal parts of a second
my @date = $date =~ /([0-9]{4})([0-9]{2})([0-9]{2})/; # Split date into year month day
my @time = $time =~ /([0-9]{2})([0-9]{2})([0-9]{2})/; # Split time into hour month second
my $formatted_date = join('-', @date) . '-' . join(':', @time); # Put it all back together
Time::Piece
是自 v5.10.0 以来一直处于核心的模块,具有可比较的日期解析/格式化 API:
use strict;
use warnings;
use feature qw(say);
use Time::Piece;
my $t = Time::Piece->strptime("20190626-102908.616319","%Y%m%d-%H%M%S");
say $t->strftime("%Y-%m-%d-%H:%M:%S");
# 2019-06-26-10:29:08
我正在编写一个从日志文件中获取数据的脚本。日志文件包含特定格式的日期字符串:
20190626-102908.616319
通过我的代码解析后,我希望日期采用另一种格式:
2019-06-26-10:29:08
我用过 DateTime::Format::Strptime
,效果很好。
但是,要求是使用另一种方式,因为将使用脚本的系统不允许安装新模块(是的,我不能安装额外的 Perl 模块)。
我唯一能合作的是Date::Parse
或Date::Format
,但我不能让它合作。
与Date::Parse
:
my $time2 = str2time($chunks[0]);
我只得到空输出。
呼叫 Date::Format
:
my $time2 = time2str("%Y-%m-%d-%H:%M:%S\n", $chunks[0]);
只给出 1970-01-01-00:00:00
.
有人能给我指出正确的方向吗?
给定 20190626-102908.616319 作为 $string
的内容my ($date,$time) = split /-/, $string; # Separate time from date
$time = int $time; # Drop decimal parts of a second
my @date = $date =~ /([0-9]{4})([0-9]{2})([0-9]{2})/; # Split date into year month day
my @time = $time =~ /([0-9]{2})([0-9]{2})([0-9]{2})/; # Split time into hour month second
my $formatted_date = join('-', @date) . '-' . join(':', @time); # Put it all back together
Time::Piece
是自 v5.10.0 以来一直处于核心的模块,具有可比较的日期解析/格式化 API:
use strict;
use warnings;
use feature qw(say);
use Time::Piece;
my $t = Time::Piece->strptime("20190626-102908.616319","%Y%m%d-%H%M%S");
say $t->strftime("%Y-%m-%d-%H:%M:%S");
# 2019-06-26-10:29:08