Given a string that represents a date/time in ISO8601 format (e.g. 20100723T073000
), I need to ultimately parse this into a user-supplied format using a general strftime
format string. In order to do that, I need to convert the ISO8601 timestamp to a Unix timestamp. There are a huge amount of date/time manipulation modules for Perl and I'm a little overwhelmed. Any suggestions on how to do this?
The getTime method returns the number of milliseconds since the Unix Epoch (1st of January, 1970 00:00:00). To get a Unix timestamp, we have to divide the result from calling the getTime() method by 1000 to convert the milliseconds to seconds. What is this?
Converting from normal date to epoch in Perl You can also use Date::Manip if you need more advanced date manipulation routines. Using the Date::Parse module (thanks to ericblue76): use Date::Parse; print str2time("02/25/2011 11:50AM");
Unix-time is always in UTC, so you never have to worry about that. Of course ISO8601 has the advantage of being human-readable when you look at the raw database and I won't have to rewrite a couple of lines of code shortly before 2038, but that does not seem to make up for the downsides.
Unix epoch timestamps are supported in the following formats: 10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message. For example, [1234567890] or [1234567890, other] followed by the rest of the message.
The champion module for handling dates, times, durations, timezones and formats is DateTime. Once you've got your DateTime object, you can perform a huge number of operations on it, like adding/subtracting other DateTime objects or DateTime::Duration objects, or printing it out in another format.
use strict; use warnings;
use DateTime;
use DateTime::Format::ISO8601;
my $dt = DateTime::Format::ISO8601->parse_datetime('20100723T073000');
print $dt->strftime('%F %T');
prints: "2010-07-23 07:30:00"
If you don't have or don't want to install the DateTime::Format::ISO8601
module, you can parse at least a subset of ISO8601 with HTTP::Date
:
$ perl -MHTTP::Date -wle 'print str2time("2013-11-30T23:05:03")'
1385845503
As with any date handling, be cautious about time zone issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With