How can I parse a string in strftime format in Perl?

I am new to Perl and I want to find out if there is an inverse function for strftime (). Look

use POSIX qw(strftime); print strftime("%YT%mT%d TTTT%H:%M:%S", localtime) 

Receive: 2009T08T14 TTTT00: 37: 02. How can I do an oposite operation? From the line "2009T08T14 TTTT00: 37: 02" to get 2009-08-14 00:37:02 knowing the format string "% YT% mT% d TTTT% H:% M:% S"?

+4
source share
3 answers

One option is to parse numbers using a regular expression, and then use Time :: Local . However, now that I understand that your question is how to go from the strftime formatted string to a point in time in general, this approach should be cumbersome.

You mentioned POSIX::strptime in your answer, 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 whatever you want with it.

+7
source

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

+2
source

So easy

 use Time::ParseDate; my $t = '2009T08T14 TTTT00:37:02'; $t =~ s/TTTT//; $t =~ s/T/-/g; $seconds_since_jan1_1970 = parsedate($t) 
0
source

All Articles