Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

后端 未结 9 1034
礼貌的吻别
礼貌的吻别 2021-01-30 02:30

When writing Perl scripts I frequently find the need to obtain the current time represented as a string formatted as YYYY-mm-dd HH:MM:SS (say 2009-11-29 14:28

相关标签:
9条回答
  • 2021-01-30 02:54

    Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

    use Time::Piece;
    print localtime->strftime('%Y-%m-%d');
    

    or without the overridden localtime:

    use Time::Piece (); 
    print Time::Piece::localtime->strftime('%F %T');
    
    0 讨论(0)
  • 2021-01-30 02:55

    Why not use the DateTime module to do the dirty work for you? It's easy to write and remember!

    use strict;
    use warnings;
    use DateTime;
    
    my $dt   = DateTime->now;   # Stores current date and time as datetime object
    my $date = $dt->ymd;   # Retrieves date as a string in 'yyyy-mm-dd' format
    my $time = $dt->hms;   # Retrieves time as a string in 'hh:mm:ss' format
    
    my $wanted = "$date $time";   # creates 'yyyy-mm-dd hh:mm:ss' string
    print $wanted;
    

    Once you know what's going on, you can get rid of the temps and save a few lines of code:

    use strict;
    use warnings;
    use DateTime;
    
    my $dt = DateTime->now;
    print join ' ', $dt->ymd, $dt->hms;
    
    0 讨论(0)
  • 2021-01-30 02:55

    In many cases, the needed 'current time' is rather $^T, which is the time at which the script started running, in whole seconds (assuming only 60 second minutes) since the UNIX epoch.

    This to prevent that an early part of a script uses a different date (or daylight-saving status) than a later part of a script, for example in query-conditions and other derived values.

    For that variant of 'current time', one can use a constant, also to document that it was frozen at compile time:

    use constant YMD_HMS_AT_START => POSIX::strftime( "%F %T", localtime $^T );
    

    Alternative higher resolution startup time:

    0+ [ Time::HiRes::stat("/proc/$$") ]->[10]
    
    0 讨论(0)
提交回复
热议问题