Update See end for an strptime
pattern to parse the shown input string format correctly
What is shown works,† and so the DateTime::Format::Strptime constructor returns a DateTime
object. But when an object is simply printed then one gets the stringification that is shown.
So you need to format it for printing as desired. A general way is with strftime
say $start_date->strftime("%F %T");
where both %F
and %T
are shorthands, see strftime patterns
Or combine the basic ymd
and hms
methods
say $start_date->ymd('-') . ' ' . $start_date->hms(':');
See the docs and adjust if/as needed. I didn't understand some details.
† It works only by accident in this exact example, since the pattern given to use for parsing in new
is wrong for the shown input format, and is also inconsistent with stated requirements
The shown pattern doesn't have a format specifier for the seconds, nor for the milliseconds that follow it, nor for the following AM/PM
-- all expected in the input string. So in general an input in the shown form cannot be parsed correctly with the shown pattern
The %H
matches 00-23
hour, so not 12-hour clock which is stated as expected and is implicit by the presence of AM
. (It still matches a 12-hour-time number but it won't once the missing AM/PM format specifier is added.)
The pattern in the OP works and parses the given input correctly because 03:45...
happens to be in AM, and the module uses regex to match the given pattern anywhere in the given string (by default), so %H:%M
matches 03:45
and the rest of the input string doesn't matter. If we turn on strict
in the constructor this'll fail. See documentation.
Assuming that the shown input is the correct part we'd need
my $strp = DateTime::Format::Strptime->new(
pattern => '%h %d %Y %I:%M:%S%3N%p'
);
Here %I
is for 12-hour clock (1-12), added %S
is for seconds and %3N
for milliseconds (see the page in docs for patterns, linked above), and %p
for AM/PM.
The rest then works as it stands, along with printing in a desired format given above.
AM
/PM
, but your example is with3:45 AM
, meaning that it is identical with 12-hour and 24-hour format, which makes your question a bit unclear. Could you add the code that does the print (it sounds like you just added an extraT
in there...), and use3:45 PM
rather than3:45 AM
as your example please?:000
beforeAM
as milliseconds; is that right? If so, will they always be000
, or can they be an arbitrary 3-digit number? (the answer will not be the same in both cases)my $start_date;
But the code is what I am using and it prints2017-04-09T03:45:00
. So I am not sure why it's not printing for you. yes the:000
is miliseconds. Yes I used AM but if you swap AM to PM i get the same result. Which I could expect to get2017-04-09T15:45:00
for PM. What I am trying to produce is2017-04-09 03:45:00
for am and2017-04-09 15:45:00
for PM.print "$start_date";
and no they are not always 000.