如何在Perl中解析strftime格式的字符串? [英] How can I parse a strftime formatted string in Perl?
问题描述
看,
使用POSIX qw(strftime);
print strftime(%YT%mT%d TTTT%H:%M:%S,localtime)
我得到:2009T08T14 TTTT00:37:02。如何做对面操作?从2009T08T14 TTTT00:37:02字符串获取2009-08-14 00:37:02,知道格式化字符串%YT%mT%d TTTT%H:%M:%S?
一个选项是使用正则表达式解析数字,然后使用 Time :: Local 。然而,现在我明白你的问题是如何从一个 strftime
格式化的字符串到一般的时间,这种方法肯定是麻烦的。
您在答案中提到 POSIX :: strptime
如果您的平台支持它是非常好的。或者,您可以使用 DateTime :: Format :: Strptime :
#!/ usr / bin / perl
use strict;
使用警告;
使用DateTime :: Format :: Strptime;
使用POSIX qw(strftime);
我的$ f =%YT%mT%d TTTT%H:%M:%S;
my $ s = strftime($ f,localtime);
打印$ s\\\
;
my $ Strp = DateTime :: Format :: Strptime-> new(
pattern => $ f,
locale =>'en_US',
time_zone =>'US / Eastern',
);
我的$ dt = $ Strp-> parse_datetime($ s);
print $ dt-> epoch,\\\
;
print scalar localtime $ dt-> epoch,\\\
;
$ dt
是一个 DateTime 对象,所以你可以做任何你想要的任何事情。
I am new to Perl and I wan to know whether there is an inverse function to the strftime(). Look,
use POSIX qw(strftime);
print strftime("%YT%mT%d TTTT%H:%M:%S", localtime)
I get: 2009T08T14 TTTT00:37:02. How can I do the oposite operation? From "2009T08T14 TTTT00:37:02" string to get 2009-08-14 00:37:02, knowing the formatting string "%YT%mT%d TTTT%H:%M:%S"?
One option is to parse the numbers using a regular expression and then use Time::Local. However, now that I understand your question is how to go from a strftime
formatted string to a time in general, that approach is bound to be cumbersome.
You mention in your answer POSIX::strptime
which is great if your platform supports it. Alternatively, you can use DateTime::Format::Strptime:
#!/usr/bin/perl
use strict;
use warnings;
use DateTime::Format::Strptime;
use POSIX qw(strftime);
my $f = "%YT%mT%d TTTT%H:%M:%S";
my $s = strftime($f, localtime);
print "$s\n";
my $Strp = DateTime::Format::Strptime->new(
pattern => $f,
locale => 'en_US',
time_zone => 'US/Eastern',
);
my $dt = $Strp->parse_datetime($s);
print $dt->epoch, "\n";
print scalar localtime $dt->epoch, "\n";
$dt
is a DateTime object so you can do pretty much whatever you want with it.
这篇关于如何在Perl中解析strftime格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!