How can I parse a strftime formatted string in Perl?

后端 未结 3 1593
无人共我
无人共我 2021-01-19 10:19

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:         


        
相关标签:
3条回答
  • 2021-01-19 10:58

    So easyy

    use Time::ParseDate;
    my $t = '2009T08T14 TTTT00:37:02';
    
    $t =~ s/TTTT//;
    $t =~ s/T/-/g;
    
    $seconds_since_jan1_1970 = parsedate($t)
    
    0 讨论(0)
  • 2021-01-19 11:00

    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.

    0 讨论(0)
  • 2021-01-19 11:09

    I think I have found the solution: strptime($strptime_pattern, $string)

    0 讨论(0)
提交回复
热议问题