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

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?

Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array?

This question is related to perl datetime parsing date time

The answer is


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.


To parse a date, look at Date::Parse in CPAN.


$ENV{TZ}="GMT";
POSIX::tzset();
$time = POSIX::mktime($s,$m,$h,$d,$mo-1,$y-1900);

I know this is an old question, but thought I would offer another answer.

Time::Piece is core as of Perl 5.9.5

This allows parsing of time in arbitrary formats via the strptime method.

e.g.:

my $t = Time::Piece->strptime("Sunday 3rd Nov, 1943",
                              "%A %drd %b, %Y");

The useful part is - because it's an overloaded object, you can use it for numeric comparisons.

e.g.

if ( $t < time() ) { #do something }

Or if you access it in a string context:

print $t,"\n"; 

You get:

Wed Nov  3 00:00:00 1943

There's a bunch of accessor methods that allow for some assorted other useful time based transforms. https://metacpan.org/pod/Time::Piece


Get Date::Manip from CPAN, then:

use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );

edit:

Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.

e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.

See the authors comments.

(Thanks to the author of the first comment below)


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!


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()


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.


There are many Date manipulation modules on CPAN. My particular favourite is DateTime and you can use the strptime modules to parse dates in arbitrary formats. There are also many DateTime::Format modules on CPAN for handling specialised date formats, but strptime is the most generic.


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()


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.


There are many Date manipulation modules on CPAN. My particular favourite is DateTime and you can use the strptime modules to parse dates in arbitrary formats. There are also many DateTime::Format modules on CPAN for handling specialised date formats, but strptime is the most generic.


I'm using a very old O/S that I don't dare install libraries onto, so here's what I use;

%MonthMatrix=("Jan",0,"Feb",31,"Mar",59,"Apr",90,"May",120,"Jun",151,"Jul",181,"Aug",212,"Sep",243,"Oct",273,"Nov",304,"Dec",334);
$LeapYearCount=int($YearFourDigits/4);
$EpochDayNumber=$MonthMatrix{$MonthThreeLetters};
if ($LeapYearCount==($YearFourDigits/4)) { if ($EpochDayNumber<32) { $EpochDayNumber--; }}
$EpochDayNumber=($YearFourDigits-1970)*365+$LeapYearCount+$EpochDayNumber+$DayAsNumber-493;
$TimeOfDaySeconds=($HourAsNumber*3600)+($MinutesAsNumber*60)+$SecondsAsNumber;
$ActualEpochTime=($EpochDayNumber*86400)+$TimeOfDaySeconds;

The input variables are;

$MonthThreeLetters
$DayAsNumber
$YearFourDigits
$HourAsNumber
$MinutesAsNumber
$SecondsAsNumber

...which should be self-explanatory.

The input variables, of course, assume GMT (UTC). The output variable is "$ActualEpochTime". (Often, I only need $EpochDayNumber, so that's why that otherwise superfluous variable sits on its own.)

I've used this formula for years with nary an error.


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:~$ 

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

Questions with perl tag:

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer "End of script output before headers" error in Apache Perl - Multiple condition if statement without duplicating code? How to decrypt hash stored by bcrypt Split a string into array in Perl Turning multiple lines into one comma separated line String compare in Perl with "eq" vs "==" how to remove the first two columns in a file using shell (awk, sed, whatever) Find everything between two XML tags with RegEx Difference between \w and \b regular expression meta characters Today's Date in Perl in MM/DD/YYYY format Best way to iterate through a Perl array Better way to remove specific characters from a Perl string The correct way to read a data file into an array Regex to match any character including new lines Search and replace a particular string in a file using Perl Grep to find item in Perl array Find size of an array in Perl Check whether a string contains a substring Perl - If string contains text? How to replace a string in an existing file in Perl? How to match a substring in a string, ignoring case Negative regex for Perl string pattern match How to print variables in Perl Why does modern Perl avoid UTF-8 by default? How to match any non white space character except a particular one? Escaping a forward slash in a regular expression Easy way to print Perl array? (with a little formatting) Submit form and stay on same page? How to use foreach with a hash reference? How to extract string following a pattern with grep, regex or perl How can I debug a Perl script? Rename Files and Directories (Add Prefix) Show a PDF files in users browser via PHP/Perl Perl regular expression (using a variable as a search string with Perl operator characters included) Perl: function to trim string leading and trailing whitespace What is the meaning of @_ in Perl? Perl read line by line How to see if a directory exists or not in Perl? How can I store the result of a system command in a Perl variable? How do I enter a multi-line comment in Perl? How do I update all my CPAN modules to their latest versions? Match whitespace but not newlines Perl: Use s/ (replace) and return new string In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file? Array initialization in Perl How can I call a shell command in my Perl script? Programmatically read from STDIN or input file in Perl How to compile a Perl script to a Windows executable with Strawberry Perl? How do I search a Perl array for a matching string?

Questions with datetime tag:

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")? How do I filter date range in DataTables? Convert a string to datetime in PowerShell How to insert current datetime in postgresql insert query How to change the datetime format in pandas Pandas: Subtracting two date columns and the result being an integer finding first day of the month in python Error in MySQL when setting default value for DATE or DATETIME How to Extract Year from DATE in POSTGRESQL java.time.format.DateTimeParseException: Text could not be parsed at index 21 How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Is there a simple way to increment a datetime object one month in Python? Pandas: Convert Timestamp to datetime.date How to insert date values into table In Oracle SQL: How do you insert the current date + time into a table? Getting today's date in YYYY-MM-DD in Python? What's the difference between Instant and LocalDateTime? How to convert string to datetime format in pandas python? What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types Format datetime to YYYY-MM-DD HH:mm:ss in moment.js How to convert an Instant to a date format? Python - Get Yesterday's date as a string in YYYY-MM-DD format python pandas extract year from datetime: df['year'] = df['date'].year is not working Create a day-of-week column in a Pandas dataframe using Python datetime to string with series in python pandas How to get current time in python and break up into year, month, day, hour, minute? How to force the input date format to dd/mm/yyyy? What exactly does the T and Z mean in timestamp? How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query How do I get the current timezone name in Postgres 9.3? Datetime current year and month in Python How to convert datetime to integer in python Convert Pandas Series to DateTime in a DataFrame Extract time from moment js object Get current date in DD-Mon-YYY format in JavaScript/Jquery Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe? Calculate time difference in minutes in SQL Server Convert Pandas Column to DateTime Inserting created_at data with Laravel

Questions with parsing tag:

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java? Pandas read_csv low_memory and dtype options How can I fix MySQL error #1064? Convert JSON String to JSON Object c# IsNumeric function in c# A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error Parse json string to find and element (key / value) Retrieving values from nested JSON Object C# Parsing JSON array of objects Parsing JSON in Java without knowing JSON format Parse String date in (yyyy-MM-dd) format Jquery Smooth Scroll To DIV - Using ID value from Link Parsing JSON array into java.util.List with Gson Parsing Json rest api response in C# Parsing a pcap file in python In C#, how to check whether a string contains an integer? How can I parse a String to BigDecimal? PHP parse/syntax errors; and how to solve them PHP CSV string to array Reading input files by line using read command in shell scripting skips last line JSON Parse File Path Parse JSON file using GSON Parsing huge logfiles in Node.js - read in line-by-line Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss Splitting on last delimiter in Python string? How to avoid warning when introducing NAs by coercion Parser Error when deploy ASP.NET application Malformed String ValueError ast.literal_eval() with String representation of Tuple Loop through all elements in XML using NodeList Finding last occurrence of substring in string, replacing that Parse (split) a string in C++ using string delimiter (standard C++) JSON response parsing in Javascript to get key/value pair Extract data from XML Clob using SQL from Oracle Database Parse a URI String into Name-Value Collection Read and parse a Json File in C# ParseError: not well-formed (invalid token) using cElementTree Read .csv file in C How to install beautiful soup 4 with python 2.7 on windows Text File Parsing with Python Parsing JSON string in Java How to parse freeform street/postal address out of text, and into components

Questions with date tag:

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer? Moment.js - How to convert date string into date? Extract Month and Year From Date in R #1292 - Incorrect date value: '0000-00-00' Extract year from date Error in MySQL when setting default value for DATE or DATETIME How to Extract Year from DATE in POSTGRESQL Format date as dd/MM/yyyy using pipes Moment.js - tomorrow, today and yesterday Can I use an HTML input type "date" to collect only a year? Formatting a Date String in React Native How to initialize a variable of date type in java? How to properly add 1 month from now to current date in moment.js How to convert dd/mm/yyyy string into JavaScript Date object? Get only records created today in laravel Add A Year To Today's Date LocalDate to java.util.Date and vice versa simplest conversion? PHP date time greater than today Convert String to Carbon Moment Js UTC to Local Time HTML Display Current date Hive cast string to date dd-MM-yyyy moment.js, how to get day of week number How to convert an Instant to a date format? Oracle SQL - DATE greater than statement Python - Get Yesterday's date as a string in YYYY-MM-DD format Get date from input form within PHP How to force the input date format to dd/mm/yyyy? Format date and Subtract days using Moment.js How to add minutes to current time in swift How to convert Moment.js date to users local timezone? How to compare LocalDate instances Java 8 Getting Current date, time , day in laravel How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Moment.js get day name from date Get current date in DD-Mon-YYY format in JavaScript/Jquery Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift How to convert a date to milliseconds Using momentjs to convert date to epoch then back to date Parsing date string in Go Java 8: Difference between two LocalDateTime in multiple units

Questions with time tag:

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object Swift convert unix time to date and time Python get current time in right timezone PHP: How to check if a date is today, yesterday or tomorrow How to parse unix timestamp to time.Time Python loop to run for certain amount of seconds Go / golang time.Now().UnixNano() convert to milliseconds? What is the `zero` value for time.Time in Go? How to extract epoch from LocalDate and LocalDateTime? how to sync windows time from a ntp time server in command Exception in thread "main" java.lang.Error: Unresolved compilation problems PHP Converting Integer to Date, reverse of strtotime How to get current time with jQuery Get current time in hours and minutes How to format current time using a yyyyMMddHHmmss format? How to print the current time in a Batch-File? Should MySQL have its timezone set to UTC? Checking Date format from a string in C# Get the time difference between two datetimes Convert Java string to Time, NOT Date Creating a timer in python How do I measure request and response times at once using cURL? How to delete last item in list? How do I use .toLocaleTimeString() without displaying seconds? Converting Milliseconds to Minutes and Seconds? How to multiply duration by integer? Oracle date format picture ends before converting entire input string How to print current date on python3? Convert java.util.date default format to Timestamp in Java What is the easiest way to get current GMT time in Unix timestamp format? Command to get time in milliseconds Creating java date object from year,month,day Current date and time as string how to re-format datetime string in php? Update TextView Every Second Current time formatting with Javascript How to measure time taken between lines of code in python? Is Android using NTP to sync time? Getting time difference between two times in PHP Does Python's time.time() return the local or UTC timestamp? PHP: How to get current time in hour:minute:second?