Matt Williams
Matt Williams

Reputation: 115

Converting timestamps in Perl

I am looking to convert timestamps such as the following

2019-01-01T02:15:00+00:00

Into Australian Eastern Standard Time in Perl. I have over 10,000 of these timestamps, any help would be really appreciated I need to input them into a mysql DB with a format of YYYY-MM-DD hh:mm:ss

Upvotes: 0

Views: 320

Answers (1)

lordadmira
lordadmira

Reputation: 1832

You would use the standard Perl module Time::Piece. It provides the standard strptime and strftime functions. The first allows you to parse a timestamp with a template and the second outputs a timestamp based on the same kind of template. To change timezones you would add or subtract the number of seconds difference.

$t = Time::Piece->strptime("2020-11-04T01:46:00", "%Y-%m-%dT%H:%M:%S");
$t += $offset;
print $t->strftime("%Y-%m-%dT%H:%M:%S");

Or if your current time is the current locale and you're always converting from GMT:

$t = Time::Piece->strptime("2020-11-04T01:46:00", "%Y-%m-%dT%H:%M:%S");
$l = localtime $t->epoch;
print $l->strftime("%Y-%m-%dT%H:%M:%S");

Now if you need to do something more complicated than that (daylight savings time, leap seconds), there is the DateTime module but it is correspondingly far more complicated to use.

See also How can I parse dates and convert time zones in Perl?

HTH

Upvotes: 2

Related Questions