tags:

views:

720

answers:

4

Hi, 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"?

+4  A: 

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.

Sinan Ünür
Ok, but whaat if I have a function whose parameter is the formatting string (here for ex. "%YT%mT%d TTTT%H:%M:%S") but I do not know it exactly..So, I am looking for the oposite of the strftime function.
Markus
Congratulations on breaking 10k Sinan!!! :)
Ether
No, just use DateTime::Format::Strptime instead.
Dave Rolsky
@Dave Rolsky Well, OK then. @Ether thanks but still 3 points short ;-) At least, I got a screenshot at 9999 points before Dave's downvote ;-)
Sinan Ünür
A: 

So easyy

use Time::ParseDate;
my $t = '2009T08T14 TTTT00:37:02';

$t =~ s/TTTT//;
$t =~ s/T/-/g;

$seconds_since_jan1_1970 = parsedate($t)
Kristoffon
+1  A: 

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

Markus
I did not know about http://search.cpan.org/dist/POSIX-strptime/ ... However, it looks like I cannot install that on Windows because `strptime` does not exist on Windows. See http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows for more information.
Sinan Ünür
Of course, you may not care about Windows. I am just mentioning it in case you are concerned about portability.
Sinan Ünür
A: 

this is an alternative to Time::Parsedate

echo "SELECT strftime('%s','$FormattedTimeString');" | sqlite3

see http://www.sqlite.org/cvstrac/wiki/wiki?p=DateAndTimeFunctions for supported formats.

Russell Square
ack, wiki formatting ate my backticks -- the grey stuff is in backticks.
Russell Square