How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

前端 未结 13 2153
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 04:20

Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT?

相关标签:
13条回答
  • 2020-12-03 04:52

    If you're using the DateTime module, you can call the epoch() method on a DateTime object, since that's what you think of as unix time.

    Using DateTimes allows you to convert fairly easily from epoch, to date objects.

    Alternativly, localtime and gmtime will convert an epoch into an array containing day month and year, and timelocal and timegm from the Time::Local module will do the opposite, converting an array of time elements (seconds, minutes, ..., days, months etc.) into an epoch.

    0 讨论(0)
  • 2020-12-03 04:52

    Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.

    If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.

    If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.

    0 讨论(0)
  • 2020-12-03 04:58

    If you're just looking for a command-line utility (i.e., not something that will get called from other functions), try out this script. It assumes the existence of GNU date (present on pretty much any Linux system):

    #! /usr/bin/perl -w
    
    use strict;
    
    $_ = (join ' ', @ARGV);
    $_ ||= <STDIN>;
    
    chomp;
    
    if (/^[\d.]+$/) {
        print scalar localtime $_;
        print "\n";
    }
    else {
        exec "date -d '$_' +%s";
    }
    

    Here's how it works:

    $ Time now
    1221763842
    
    $ Time yesterday
    1221677444
    
    $ Time 1221677444
    Wed Sep 17 11:50:44 2008
    
    $ Time '12:30pm jan 4 1987'
    536790600
    
    $ Time '9am 8 weeks ago'
    1216915200
    
    0 讨论(0)
  • 2020-12-03 04:59

    My favorite datetime parser is DateTime::Format::ISO8601 Once you've got that working, you'll have a DateTime object, easily convertable to epoch seconds with epoch()

    0 讨论(0)
  • 2020-12-03 04:59

    For further reference, a one liner that can be applied in, for example, !#/bin/sh scripts.

    EPOCH="`perl -e 'use Time::Local; print timelocal('${SEC}','${MIN}','${HOUR}','${DAY}','${MONTH}','${YEAR}'),\"\n\";'`"
    

    Just remember to avoid octal values!

    0 讨论(0)
  • 2020-12-03 04:59

    A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:

    martind@whitewater:~$ cat `which isoToEpoch`
    #!/usr/bin/perl -w
    use strict;
    use Time::Piece;
    # sudo apt-get install libtime-piece-perl
    while (<>) {
      # date --iso=s:
      # 2007-02-15T18:25:42-0800
      # Other matched formats:
      # 2007-02-15 13:50:29 (UTC-0800)
      # 2007-02-15 13:50:29 (UTC-08:00)
      s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
      print;
    }
    martind@whitewater:~$ 
    
    0 讨论(0)
提交回复
热议问题