Chapter 9. Date Arithmetic
This chapter continues the example begun in Chapter 8. In that chapter, we created a script to
extract information from each line of our web server’s access
log, and began work on the code to assemble “visit”
statistics from that information. We had just reached the point where
we wanted to use a subroutine called
&get_seconds
to convert from the date and time
string included in our log file entries to something called the
Epoch
seconds
. This &get_seconds
subroutine is our first real exposure to the notion of date
arithmetic
. Let’s take a brief detour to
look at that subject in more detail.
Date/Time Conversions
The idea with date arithmetic is that
it’s much easier to do things like finding the interval between
two date/time strings if you first convert those strings into a
common format. The format of choice in this case is the Epoch
seconds, which is the number of seconds since some specific point in
time, called the Epoch
. (On most Unix systems,
the Epoch is 00:00:00 GMT/UTC on January 1, 1970.)
If you want to get the number of Epoch seconds corresponding to the
current time, you can get it by using Perl’s
time
function, as in:
$seconds = time;
Two other Perl functions called
localtime
and gmtime
can be used to convert Epoch seconds into human-readable
local time or GMT (respectively). You may recall looking at
localtime
briefly in Chapter 6;
now we’re going to look at it in more detail. Example 9-1
shows localtime
and
gmtime
in action. (As usual, ...
Get Perl for Web Site Management now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.