Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an ISO8601 timestamp into unix time in Perl?

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?

like image 541
Jimmy Avatar asked Jun 24 '10 20:06

Jimmy


People also ask

How do I convert timestamp to time in Unix?

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?

How do I convert date to epoch time in Perl?

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");

What are the differences between ISO 8601 and Unix Epoch time formats?

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.

What is the format of Unix timestamp?

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.


2 Answers

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"

like image 69
Ether Avatar answered Sep 29 '22 01:09

Ether


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.

like image 33
tuomassalo Avatar answered Sep 29 '22 01:09

tuomassalo