cpan intermediate

How to parse date string with DateTime::Format::Strptime?

Question

How to parse date string with DateTime::Format::Strptime?

Since the DateTime::Format::Strptime module is not a core Perl module and is not available in a restricted sandbox without CPAN access, you cannot rely on it directly in such an environment. However, you can parse simple date strings using core Perl functions and regex, then build a DateTime object if DateTime is installed, or simply process the date parts manually.

Below is an example that parses a date/time string of the format YYYY-MM-DD HH:MM:SS using a regex (which is core Perl) and then prints the extracted parts. This approach reflects Perl's TMTOWTDI ("There's more than one way to do it") philosophy by showing a minimal core Perl solution without external dependencies.

Core Perl Date Parsing Using Regex


use strict;
use warnings;

my $date_string = '2024-06-09 14:33:00';

# Use a regex to capture year, month, day, hour, minute, second
if ($date_string =~ /^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/) {
    my ($year, $month, $day, $hour, $minute, $second) = ($1, $2, $3, $4, $5, $6);

    print "Year: $year\n";
    print "Month: $month\n";
    print "Day: $day\n";
    print "Hour: $hour\n";
    print "Minute: $minute\n";
    print "Second: $second\n";
} else {
    print "Date string format not recognized.\n";
}

Explanation

  • The regex ^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$ captures the expected date and time parts from the string.
  • Each capture group corresponds to a numeric component of the date/time.
  • We then print the components individually — similar to accessing DateTime methods but done manually.
  • This solution requires no modules beyond core Perl and runs in any standard Perl 5 environment.

Common Pitfalls

  • Regex-based parsing assumes the format exactly matches your pattern.
  • No timezone or locale awareness is handled here.
  • If you need date arithmetic or formatting, additional code or external modules would be needed (unavailable in sandbox).

While DateTime::Format::Strptime is elegant and powerful for complex parsing, this core Perl approach is the safest fallback in restricted environments. It demonstrates the Perl way—flexible and pragmatic—without external dependencies.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 7ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Year: 2024
Month: 06
Day: 09
Hour: 14
Minute: 33
Second: 00
STDERR
(empty)

Was this helpful?

Related Questions