Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Assigning a parsed date to a variable

by 1nickt (Canon)
on Mar 30, 2017 at 21:47 UTC ( [id://1186549]=note: print w/replies, xml ) Need Help??


in reply to Assigning a parsed date to a variable

Hi, you said:

unless there is a more efficient way of doing it

Unless you are working on your regexp-fu, I would suggest not using a regexp to parse dates. Efficiency extends to future readability of your code.

Just use DateTime::Format::Strptime to make a parser with the format you want and eval to see if the string parses into a DateTime object.

Here's an SSCCE that demonstrates:

use strict; use warnings; use feature qw/ say state /; use DateTime::Format::Strptime; for ( <DATA> ) { chomp; say sprintf '%-24s: %s', $_, validate( $_ ) ? 'OK' : 'Not OK'; } sub validate { state $parser = DateTime::Format::Strptime->new( pattern => '%F %T.%3N', on_error => 'croak', ); return eval { $parser->parse_datetime( @_ ); 1 }; } __DATA__ 2017-01-29 11:30:07.370 2017-01-29 11:30:07.000 2017-01-32 11:30:07.370 2017-01-29 11:30:07 foo bar
Edit: Or, declare the parser without the on_error attribute, and then you can use the DateTime object, if you can parse a date from your string. Presumably you want to use the date after you've found it.
my $str = '2017-01-29 11:30:07.370'; $parser = DateTime::Format::Strptime->new( pattern => '%F %T.%3N' ); if ( my $dt = $parser->parse_datetime( $str ) ) { say "Interestingly, $str falls on a " . $dt->day_name; } else { say "$str is not a valid date"; }

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Assigning a parsed date to a variable
by shmem (Chancellor) on Mar 30, 2017 at 21:54 UTC

    TIMTOWTDI, of course ;-)

    use Date::Parse; my $adate = "2017-01-29 11:30:07.370" my $new_datetime = str2time $adate; print $new_datetime,$/; __END__ 1485685807.37
    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1186549]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-25 10:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found