Bart
Bart

Reputation: 135

Perl - convert string to datetime

I'm working on a script that fetches data from a log file. The log file contains date string in a particular format:

20190626-102908.616319

Once it's parsed through my code, I want the date to be in another format:

2019-06-26-10:29:08

I've used DateTime::Format::Strptime and that works perfectly.

BUT, the requirement is to use another way as the system the script will be used on does not allow installing new modules (yeah, I cannot install additional Perl modules).

The only thing I can work with would be Date::Parse or Date::Format, but I cannot make it cooperate.

With Date::Parse:

my $time2 = str2time($chunks[0]);

I only get empty output.

Calling Date::Format:

my $time2 = time2str("%Y-%m-%d-%H:%M:%S\n", $chunks[0]);

gives just 1970-01-01-00:00:00.

Could anyone point me into right direction here?

Upvotes: 1

Views: 1343

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61512

Time::Piece is a module that has been in core since v5.10.0 and has comparable date parsing / formatting APIs:

use strict; 
use warnings; 

use feature qw(say);
use Time::Piece; 

my $t = Time::Piece->strptime("20190626-102908.616319","%Y%m%d-%H%M%S");
say $t->strftime("%Y-%m-%d-%H:%M:%S");
# 2019-06-26-10:29:08

Upvotes: 2

JGNI
JGNI

Reputation: 4013

Given 20190626-102908.616319 as the content of $string

my ($date,$time) = split /-/, $string; # Separate time from date
$time = int $time; # Drop decimal parts of a second
my @date = $date =~ /([0-9]{4})([0-9]{2})([0-9]{2})/; # Split date into year month day
my @time = $time =~ /([0-9]{2})([0-9]{2})([0-9]{2})/; # Split time into hour month second
my $formatted_date = join('-', @date) . '-' . join(':', @time); # Put it all back together

Upvotes: 1

Related Questions