Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Parsing a date time string

by bangor (Monk)
on Aug 02, 2014 at 16:27 UTC ( [id://1096020]=perlquestion: print w/replies, xml ) Need Help??

bangor has asked for the wisdom of the Perl Monks concerning the following question:

In my script I need to accept date time strings in three formats:
2014-07-12 2014-07-12 1:00 2014-07-12 01:00
In this example I need to change "1:00" to "01:00" before passing to a DB query. This is how I am doing it:
sub parse_time { my $time = shift; return $time unless $time =~ m/\d{1,2}:\d{2}$/; return $time if $time =~ m/\d{2}:\d{2}$/; $time =~ s/(\d{1}:\d{2})$/0$1/; return $time; }
It works, but it feels kludgy - any advice appreciated.

Replies are listed 'Best First'.
Re: Parsing a date time string
by Corion (Patriarch) on Aug 02, 2014 at 16:35 UTC

    Why not fix the time unconditionally?

    sub fix_time { my( $time )= @_; $time =~ s/^(\d:\d\d)$/0$1/; return $time };

    This replaces (if it finds) the leading single-digit number with a zero-padded number.

      Thanks Corion, far more elegant. I made a small adjustment so it could accept the whole string:
      sub fix_time { my $time = shift; $time =~ s/\s(\d:\d\d)$/ 0$1/; return $time; }
Re: Parsing a date time string
by Lennotoecom (Pilgrim) on Aug 02, 2014 at 18:44 UTC
    while (<DATA>){ printf "%04d-%02d-%02d %02d:%02d\n", m/\d+/g; } __DATA__ 2014-07-1 2014-7-09 1:3 2014-07-12 01:5
    output !
    2014-07-01 00:00 2014-07-09 01:03 2014-07-12 01:05
Re: Parsing a date time string
by CountZero (Bishop) on Aug 02, 2014 at 22:48 UTC
    DateTime::Format::Natural can read many different formats of date and time strings and returns a DateTime object.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2026-03-17 00:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.