Using POSIX::strftime vs. localtime + some custom formatting to generate a timestamp in perl

Publish date: 2024-05-04

I'm trying to generate a timestamp based on system time in perl in "YYYY-MM-DD HH:MM:SS" format and currently using the POSIX module to do that:

require POSIX; $timestamp = POSIX::strftime('%F %T', localtime); 

There is an alternative to this which is a little more primitive:

my ($s,$min,$h,$d,$m,$y) = (localtime)[0..5]; $y += 1900; $m = sprintf('%.2d', ++$m); $d = sprintf('%.2d', $d); $h = sprintf('%.2d', $h); $min = sprintf('%.2d', $min); $s = sprintf('%.2d', $s); $timestamp = "$y-$m-$d $h:$min:$s"; 

All I need is to generate the timestamp in the above format but cannot decide which approach to use. This code is expected to run on multiple platforms (including Linux) and at a reasonably high frequency. I am thinking of using $^O to evaluate the OS name and using the former for Linux and latter for all else.

What are the benefits/drawbacks of each (other than more lines of code obviously). I'd be grateful if someone more knowledgeable in Perl could point me in the right direction. I have searched over the internet and perldocs but could not find the answer. It would be very helpful if someone can answer this directly or point me to a resource (website/blog/book) that could help me with this.

Many thanks in advance.

2 Answers

If we clean up your code snippets and make them portable (by avoiding %F and %T), we get

use POSIX qw( strftime ); my $timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime); 

and

my ($sec, $min, $hour, $day, $month, $year) = localtime; my $timestamp = sprintf("%d-%02d-%02d %02d:%02d:%02d", $year+1900, $month+1, $day, $hour, $min, $sec); 

I would use the former because it's much simpler. This is true regardless of the OS.

1

This is an alternative solution that uses the same underlying C library as the solutions ikegami explained. I have not done any benchmarking to see which one is faster or more efficient.

You can also use Time::Piece, which has been in core since Perl 5.10. It upgrades the return value of localtime to an object with handy methods. You can use those directly on the return value without assigning it to a variable.

use Time::Piece; my $timestamp = localtime->strftime('%Y-%m-%d %H:%M:%S'); # Neither %F nor %T work on Windows. 
4

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoanJuZGqFcYKOrqqippdivbC%2FyLGqraqWqbausYyvqmakn5iurcDIppxmq5%2Bism6v1KyrqKVdm7yzucCtq6Kml2LBsHnGnqWeqpGpsm6tjK2gpp2j