Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a timestamp in Perl?

I would like to get this timestamps formatting:

01/13/2010 20:42:03 - -

Where it's always 2 digits for the number except for the year, where it's 4 digits. And it's based on a 24-hour clock.

How can I do this in Perl? I prefer native functions.

like image 374
Brian Avatar asked Jan 27 '10 18:01

Brian


People also ask

How do I add a timestamp in Perl?

Creating a Timestamp Timestamp can be created by creating a DateTime object and then calling the now constructor. my $datetime = DateTime->now; print "$datetime\n" ; A DateTime object can also be created by providing all the details part wise like date, hour, minute, second, etc.

How do you format time?

4-digit year, month, day, 24-based hour, minute, second -- usually with leading zeroes. These six are the easiest formats to use and remember in Time::Format: yyyy , mm , dd , hh , mm , ss .

What is Strftime in Perl?

You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier. Replaced by.


1 Answers

POSIX provides strftime:

$ perl -MPOSIX -we 'print POSIX::strftime("%m/%d/%Y %H:%M:%S\n", localtime)'
01/27/2010 14:02:34

You might be tempted to write something like:

my ($sec, $min, $hr, $day, $mon, $year) = localtime;
printf("%02d/%02d/%04d %02d:%02d:%02d\n", 
       $day, $mon + 1, 1900 + $year, $hr, $min, $sec);

as a means of avoiding POSIX. Don't! AFAIK, POSIX.pm has been in the core since 1996 or 1997.

like image 132
Sinan Ünür Avatar answered Oct 01 '22 08:10

Sinan Ünür