Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 43 ยท Arrays and Hashes

Dates and Times

Work with dates and times in Perl: time, localtime, gmtime, POSIX strftime, Time::Piece, Time::Local, and when to reach for the DateTime module.

Almost every real program needs to know what time it is, format a date for a report, or work out how many days lie between two events. Perl handles all of this with a small set of built-in functions, and a few core modules that make the work pleasant.

Time handling in Perl starts with one idea: the epoch. Perl measures time as a plain number of seconds since 1 January 1970, 00:00:00 UTC. Every other form (a calendar date, a string like 2023-11-14) is converted from or to that number. This lesson shows the conversions you will use most.

Perl is not installed on this site, so the Perl code below is read-only, and its output was produced by a real Perl 5.42 run. The interactive examples use Python, which has the same ideas (epoch seconds, broken-down time, strftime), so you can experiment with the concepts.

Three ways to see a moment

Epoch One number, seconds since 1970.
Broken down A list of year, month, day, hour and more.
Formatted A string like 2023-11-14 22:13:20.

Perl converts between all three.

1 / 2

The current time with time

The built-in time returns the epoch seconds for right now. It takes no arguments and is cheap to call.

PERL
use v5.36;
my $now = time;
say "Seconds since 1970: $now";

Because it is a plain number, you can measure how long something took by subtracting two readings:

PERL
use v5.36;
my $start = time;
# ... do some work ...
my $elapsed = time - $start;
say "That took $elapsed seconds";

time only has whole-second precision. For fractions of a second use Time::HiRes, a core module that exports a more precise time.

Breaking time down with localtime and gmtime

localtime and gmtime turn epoch seconds into calendar parts. localtime uses the computer's time zone and gmtime uses UTC. In list context, each returns nine values:

PERL
use v5.36;

my $t = 1700000000;   # a fixed moment, so the output never changes
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime($t);

printf "%04d-%02d-%02d %02d:%02d:%02d\n",
    $year + 1900, $mon + 1, $mday, $hour, $min, $sec;
say "weekday=$wday day-of-year=$yday";
TEXT
2023-11-14 22:13:20
weekday=2 day-of-year=317

Three details trip up almost everyone, so memorize them:

  • $year is the number of years since 1900, so add 1900.
  • $mon runs from 0 (January) to 11 (December), so add 1 to show a month number.
  • $wday runs from 0 (Sunday) to 6 (Saturday), and $yday is zero-based too (January 1 is 0).

Without arguments, localtime uses the current time. In scalar context, it returns a readable string instead of a list. That is a perfect example of the context rules from Context: Scalar vs List:

PERL
say scalar gmtime(1700000000);
TEXT
Tue Nov 14 22:13:20 2023

Use scalar to force the string form inside say or print, which otherwise supply list context.

Try the same breakdown

Python's time.gmtime returns the same nine fields, but with friendlier numbers: the year is the full year and the month starts at 1. This stand-in shows the Perl adjustments side by side.

Python Stand-in: broken-down time and the Perl offsets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Formatting with strftime

Building strings by hand with printf works, but the strftime function from the core POSIX module is easier and handles names of days and months. You give it a format and the same list that localtime or gmtime returns:

PERL
use POSIX qw(strftime);

my @parts = gmtime(1700000000);
say strftime("%Y-%m-%d %H:%M:%S", @parts);
say strftime("%A, %d %B %Y", @parts);
say strftime("%j %a %b", @parts);
TEXT
2023-11-14 22:13:20
Tuesday, 14 November 2023
318 Tue Nov

The common format codes are:

Code Meaning Example
%Y four-digit year 2023
%m month, 01 to 12 11
%d day of month, 01 to 31 14
%H %M %S hour (24-hour), minute, second 22 13 20
%A / %a full / short weekday name Tuesday / Tue
%B / %b full / short month name November / Nov
%j day of year, 001 to 366 318

Notice that %j printed 318 while $yday was 317. strftime counts days from 1, the list value from 0. Names such as Tuesday follow your locale, so the output may be in another language on a computer that is configured that way.

Going the other way with Time::Local

To convert a calendar date into epoch seconds, use Time::Local, another core module. timegm reads its arguments as UTC and timelocal reads them in the local zone. The arguments are in the same order as the list from gmtime, with the same odd rules for month:

PERL
use Time::Local qw(timegm);

my $epoch = timegm(0, 30, 8, 15, 2, 2024);   # 08:30:00 on 15 March 2024
say $epoch;
TEXT
1710491400

The month 2 means March, because months are zero-based. A four-digit year is accepted here and is the safest form. This conversion is the usual first step when you want to compare dates or add days.

The friendlier way: Time::Piece

Time::Piece is a core module that wraps all of this in objects with readable methods. Loading it replaces the built-in localtime and gmtime with versions that return an object. When you print the object, you still get the familiar string.

PERL
use v5.36;
use Time::Piece;
use Time::Seconds;

my $t = gmtime(1700000000);

say $t->ymd;             # 2023-11-14
say $t->hms;             # 22:13:20
say $t->year;            # 2023
say $t->mon;             # 11  (a real month number)
say $t->monname;         # Nov
say $t->fullmonth;       # November
say $t->wdayname;        # Tue
say $t->strftime("%d/%m/%Y");

my $later = $t + ONE_DAY * 10;
say $later->ymd;         # 2023-11-24
TEXT
2023-11-14
22:13:20
2023
11
Nov
November
Tue
14/11/2023
2023-11-24

Here year and mon are already the values you would show people, so there is no need to add 1900 or 1. Adding ONE_DAY * 10 (a constant from Time::Seconds) moves the date ten days forward. Constants such as ONE_HOUR, ONE_DAY and ONE_WEEK exist for the same reason.

Parsing a date string

strptime is the reverse of strftime: it reads text using a format and returns an object.

PERL
my $when = Time::Piece->strptime("2024-03-15 08:30:00", "%Y-%m-%d %H:%M:%S");
say $when->epoch;        # 1710491400
say $when->datetime;     # 2024-03-15T08:30:00

my $diff = $when - $t;   # a Time::Seconds object
say int($diff->days);    # 121

Subtracting two Time::Piece objects gives a Time::Seconds object, which can report the gap as ->seconds, ->minutes, ->hours or ->days. Methods such as add_months(1) also exist, and they handle month lengths for you.

The date arithmetic below is the same idea in Python. It parses a string, subtracts two moments, and shows both the whole days and the total seconds.

Python Stand-in: parse, subtract and format dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

UTC or local time?

A good habit is to store and compare times as epoch seconds or in UTC, and convert to local time only when you show them to a person. Local time changes when daylight saving begins or ends, and a date that exists in one zone may be missing or repeated in another. If your program logs events, gmtime and ISO-style strings such as 2023-11-14T22:13:20Z avoid arguments later.

When to use DateTime

Time::Piece handles everyday needs, but it has limits: its time zone support is basic, and it is awkward for calendar rules like "the third Friday of each month". For serious work, install the DateTime distribution from CPAN (see CPAN and Dependency Management). It is a thorough, well-tested library with real time zone names, durations, and calendar math:

PERL
use DateTime;

my $dt = DateTime->new(year => 2024, month => 3, day => 15, time_zone => 'UTC');
my $next = $dt->clone->add(months => 1);
say $next->ymd;   # 2024-04-15

DateTime is not part of the core distribution, so your computer needs it installed first. It is heavier to load than Time::Piece, which is why small scripts often stay with the core modules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In list context, localtime returns the year as 123 for 2023. What do you do to display the real year?

    The year field counts years since 1900, so adding 1900 gives 2023.
  2. 2. What does scalar localtime return?

    In scalar context, localtime and gmtime return a human-readable date string. Without Time::Piece loaded, it is never an object.
  3. 3. Which core module gives strftime for formatting dates?

    strftime lives in POSIX. Time::Local converts calendar dates to epoch seconds, and Time::HiRes gives fractional-second timing.
  4. 4. In timegm(0, 30, 8, 15, 2, 2024), which month is meant?

    Months are zero-based in this argument order, so 2 means March.
  5. 5. What is the safest way to store timestamps that will be compared later?

    Epoch seconds and UTC do not change with daylight saving or the viewer's zone, so comparisons stay correct.

Summary

  • time returns epoch seconds; localtime and gmtime break them into nine fields, or a string in scalar context.
  • Remember the offsets: year is minus 1900, month is zero-based, and weekday starts at 0 for Sunday.
  • POSIX::strftime formats dates, and Time::Local converts calendar parts back into epoch seconds.
  • Time::Piece adds objects, readable methods, parsing with strptime, and date arithmetic.
  • Store times in UTC or as epoch seconds, and use the CPAN DateTime module for time zones and complex calendar rules.

Next, learn how programs make decisions in Conditionals.