masterial
masterial

Reputation: 2216

How do I convert datetime to a different format? [perl]

Need help parsing the datetime stamp and splitting it up by date and time.

use strict;
use warnings;
use Time::Piece;

my $string = "05:57:03 08/31/10 MDT";

print $string,"\n";

my $time = Time::Piece->strptime($string, "%H:%M:%S");
my $date = Time::Piece->strptime($string, "%Y/%m/%d");

print $time,$date,"\n";

Thanks! Also how do I figure out which day of week this is using code?

Upvotes: 1

Views: 6897

Answers (2)

daxim
daxim

Reputation: 39158

use DateTime::Format::Strptime;
my $s  = DateTime::Format::Strptime->new(pattern => '%T %D %Z');
my $dt = $s->parse_datetime('05:57:03 08/31/10 MDT');
say $dt->strftime('%A'); # Tuesday

Upvotes: 7

David Precious
David Precious

Reputation: 6553

You should be able to use code like the following:

my $t = Time::Piece->strptime($string, "%H:%M:%S %m/%d/%y %Z");

However, on my system at least, I have to change the time zone MST to GMT for it to match; if I leave it as in your example, I get an error:

Perl> my $t = Time::Piece->strptime("05:57:03 08/31/10 DST", "%H:%M:%S %m/%d/%y %Z");
[!] Runtime error: Error parsing time at /usr/local/lib/perl/5.10.0/Time/Piece.pm line 469.

If it works for you, though, you'll have a Time::Piece object, on which you can call e.g. $t->day_of_week for the day of the week as a number, $t->day for e.g. 'Tue', or $t->fullday for e.g. 'Tuesday'.

See the documentation for Time::Piece for details on the methods you can call.

Upvotes: 3

Related Questions