DelphiFAQ Home Search:

perl code to generate a time stamp for a unique file name


comments7 comments. Current rating: 4 stars (2 votes). Leave comments and/ or rate it.


I need some perl code to generate a time stamp for a unique file name. Can you help out?


Use the function below which returns a date/ time as a string.
The first line shows how to use the function.

$unique_filename = '~/report_' . get_timestamp();

sub get_timestamp {
   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
   if ($mon < 10) { $mon = "0$mon"; }
   if ($hour < 10) { $hour = "0$hour"; }
   if ($min < 10) { $min = "0$min"; }
   if ($sec < 10) { $sec = "0$sec"; }

   return $year . '_' . $mon . '_' . $mday . '__' . $hour . '_' . $min . '_' . $sec;

Content-type: text/html


2006-10-04, 06:54:51
anonymous from Russian Federation  
...and what if 2 requests at one second occur?
2008-03-28, 17:32:11   (updated: 2008-03-28, 17:35:05)
anonymous from United States  
Shouldn't $mday be zero-justified as well? There should be one more line in there to make it consistent:

if ($mday < 10) { $mday = ''0$mday''; }

2008-05-02, 14:53:51
anonymous from United States  
Several problems here:

1) $wday,$yday,$isdst should be 'undef,undef,undef', as they're not used and might throw a warning.
2) $mon needs to be incremented: $mon++; #january is 0, right?
2008-08-07, 05:42:13
anonymous from Pakistan  
Thanks for the post. Just an alternate of the same script:

sub get_timestamp {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);


return $year . sprintf('%02u%02u_%02u%02u%02u', $mon, $mday, $hour, $min, $sec);
2008-08-20, 04:16:45   (updated: 2008-08-20, 04:31:22) from Bangalore, India  
In above code will show month as number -1.
Following code is varation of above
$unique_filename = 'filename_' . get_timestamp();

sub get_timestamp {
@abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
retu' $mday\_$abbr[$mon]\_$year\_$hour\_$min\_$sec';


With Regards

2010-04-01, 16:20:35
anonymous from United States  
just want to say thanks for posting this

JUST what i was looking for in a current project

saved me some time!

2012-11-12, 05:11:41
coach001 from United States  



NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: