http://qs321.pair.com?node_id=93258

peschkaj has asked for the wisdom of the Perl Monks concerning the following question: (dates and times)

How do I incorporate a timestamp into a file name?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I incorporate a timestamp into a file name?
by particle (Vicar) on Jul 03, 2001 at 00:24 UTC
    i prefer
    use POSIX; use constant DATETIME => strftime("%Y-%m-%d_%H-%M-%S", localtime);
    this returns something like "2001-07-02_15-07-32"

    i use this to name temp directories, like

    my $tmpdir = $ENV{TMP} . '/' . basename $0 . '.' . DATETIME . '.' . $$
    which gives me a uniquely named dir. then my named temp files are more human readable, because i don't need the date/time string in their names.

    ~Particle

Re: How do I incorporate a timestamp into a file name?
by mikeB (Friar) on Jul 02, 2001 at 22:23 UTC
    # grab the current time my @now = localtime(); # rearrange the following to suit your stamping needs. # it currently generates YYYYMMDDhhmmss my $timeStamp = sprintf("%04d%02d%02d%02d%02d%02d", $now[5]+1900, $now[4]+1, $now[3], $now[2], $now[1], $now[0]); # insert stamp into constant portion of file name. # the constant portion of the name could be included # in the sprintf() above. my $fileName = "File$timeStamp.log";
Re: How do I incorporate a timestamp into a file name?
by bikeNomad (Priest) on Jul 02, 2001 at 22:20 UTC
    The easiest way to do it (assuming you don't need to have humans interpret it) is to just use the numeric return value from time():

    my $filename = $directory . '/' . time() . '.ext';
    Otherwise, you can put together the various numbers from localtime:

    my @lt = localtime(time); my $filename = sprintf "%s/%04d%02d%02d%02d%02d%02d", $directory, $lt[ +5]+1900, $lt[4]+1, @lt[3,2,1,0];
Re: How do I incorporate a timestamp into a file name?
by DeadPoet (Scribe) on Jan 08, 2011 at 17:52 UTC

    For a standard implementation that may be reused throughout the program:

    Example

    use Time::localtime; sub timestamp { my $t = localtime; return sprintf( "%04d-%02d-%02d_%02d-%02d-%02d", $t->year + 1900, $t->mon + 1, $t->mday, $t->hour, $t->min, $t->sec ); } print '[' . timestamp() . ']: my message'. "\n";

    Output:

    [2011-01-08_11-48-29]: my message