Reputation: 73
How do I parse a date/time format using the strptime() function?
The data/time format to be converted is: e.g. Tue Jan 16 11:18:20 + 000 2018
Upvotes: 4
Views: 3590
Reputation: 7526
The man pages for strptime show the API details as well as an example for C.
In Perl, the Time::Piece module (which is part of the Perl core), provides the strptime
function. Examples are contained in the module's documentation.
For example, this Perl snippet will convert the date as formatted to an ISO 8601 notation:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t = Time::Piece->strptime
("Tue Jan 16 11:18:20 +0000 2018", "%a %b %d %H:%M:%S %z %Y");
print $t->strftime("%Y-%m-%dT%H:%M:%S\n");
...producing the output:
2018-01-16T11:18:20
A shorthand way of producing the ISO date is simply:
print $t->datetime, "\n";
whereas you can obtain the corresponding epoch seconds thusly:
print $t->epoch, "\n";
Thus,strptime
converts a string of a time's description (its first argument) into its components, based upon the definition of its pieces in its second argument. strftime
is the converse operation, converting time components of a time structure loaded by strptime
, into a string description.
Upvotes: 4