A Python program can handle time in several ways. Time intervals are floating-point numbers in units of seconds (a fraction of a second is the fractional part of the interval): all standard library functions accepting an argument that expresses a time interval in seconds accept a float as the value of that argument. Instants in time are expressed in seconds since a reference instant, known as the epoch. (Midnight, UTC, of January 1, 1970, is a popular epoch used on both Unix and Windows platforms.) Time instants often also need to be expressed as a mixture of units of measurement (e.g., years, months, days, hours, minutes, and seconds), particularly for I/O purposes. I/O, of course, also requires the ability to format times and dates into human-readable strings, and parse them back from string formats.
This chapter covers the time
module, which supplies Python’s core time-handling functionality. The time
module is somewhat dependent on the underlying system’s C library. The chapter also presents the datetime
, sched
, and calendar
modules from the standard Python library, and the third-party modules dateutil
and pytz
.
The underlying C library determines the range of dates that the time
module can handle. On Unix systems, years 1970 and 2038 are typical cut-off points, a limitation that datetime
avoids. Time instants are normally specified in UTC (Coordinated Universal Time, once known as GMT, or Greenwich Mean Time). The time
module also supports local time zones and daylight saving time (DST), but only to the extent the underlying C system library does.
As an alternative to seconds since the epoch, a time instant can be represented by a tuple of nine integers, called a timetuple. (Timetuples are covered in Table 12-1.) All items are integers: timetuples don’t keep track of fractions of a second. A timetuple is an instance of struct_time
. You can use it as a tuple, and you can also access the items as the read-only attributes x
.tm_year
, x
.tm_mon
, and so on, with the attribute names listed in Table 12-1. Wherever a function requires a timetuple argument, you can pass an instance of struct_time
or any other sequence whose items are nine integers in the right ranges (all ranges in the table include both lower and upper bounds).
Item | Meaning | Field name | Range | Notes |
---|---|---|---|---|
0 |
Year |
|
1970–2038 |
Wider on some platforms. |
1 |
Month |
|
1–12 |
|
2 |
Day |
|
1–31 |
|
3 |
Hour |
|
0–23 |
|
4 |
Minute |
|
0–59 |
|
5 |
Second |
|
0–61 |
|
6 |
Weekday |
|
0–6 |
|
7 |
Year day |
|
1–366 |
Day number within the year. |
8 |
DST flag |
|
–1 to 1 |
|
To translate a time instant from a “seconds since the epoch” floating-point value into a timetuple, pass the floating-point value to a function (e.g., localtime
) that returns a timetuple with all nine items valid. When you convert in the other direction, mktime
ignores redundant items six (tm_wday
) and seven (tm_yday
) of the tuple. In this case, you normally set item eight (tm_isdst
) to -1
so that mktime
itself determines whether to apply DST.
time
supplies the functions and attributes listed in Table 12-2.
asctime |
Accepts a timetuple and returns a readable 24-character string such as |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
clock |
Returns the current CPU time as a floating-point number of seconds, but is platform dependent. Deprecated in v3. To measure computational costs of different approaches, use the standard library module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ctime |
Like |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
gmtime |
Accepts an instant expressed in seconds since the epoch and returns a timetuple |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
localtime |
Accepts an instant expressed in seconds since the epoch and returns a timetuple |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
mktime |
Accepts an instant expressed as a timetuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.a DST, the last item in |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
monotonic |
v3 only. Like |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
perf_counter |
v3 only. Returns the value in fractional seconds using the highest-resolution clock available to get accuracy for short durations. It is system-wide and includes time elapsed during |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
process_time |
v3 only. Returns the value in fractional seconds using the highest-resolution clock available to get accuracy for short durations. It is process-wide and doesn’t include time elapsed during |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
sleep |
Suspends the calling thread for |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
strftime |
Accepts an instant expressed as a timetuple in local time and returns a string representing the instant as specified by string
For example, you can obtain dates just as formatted by
You can obtain dates compliant with RFC 822 (e.g.,
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
strptime |
Parses |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
time |
Returns the current time instant, a |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
timezone |
The offset in seconds of the local time zone (without DST) from UTC ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
tzname |
A pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
a |
datetime
provides classes for modeling date and time objects, which can be either aware of time zones or naive (the default). The class tzinfo
, whose instances model a time zone, is abstract: the module datetime
supplies no implementation (for all the gory details, see the online docs). See the module pytz
, in “The pytz Module”, for a good, simple implementation of tzinfo
, which lets you easily create time zone-aware datetime
objects. All types in datetime
have immutable instances: attributes are read-only, and instances can be keys in a dict
or items in a set
.
Instances of the date
class represent a date (no time of day in particular within that date), are always naive, and assume the Gregorian calendar was always in effect. date
instances have three read-only integer attributes: year
, month
, and day
:
date |
The
|
Instances of the date
class support some arithmetic: the difference between date
instances is a timedelta
instance; you can add or subtract a timedelta
to/from a date
instance to make another date
instance. You can compare any two instances of the date
class (the later one is greater).
An instance d
of the class date
supplies the following methods:
ctime |
Returns a string representing the date |
isocalendar |
Returns a tuple with three integers (ISO year, ISO week number, and ISO weekday). See the ISO 8601 standard for more details about the ISO (International Standards Organization) calendar. |
isoformat |
Returns a string representing date |
isoweekday |
Returns the day of the week of date |
replace |
Returns a new
|
strftime |
Returns a string representing date
|
timetuple |
Returns a time tuple corresponding to date |
toordinal |
Returns the proleptic Gregorian ordinal for date
|
weekday |
Returns the day of the week of date |
Instances of the time
class represent a time of day (of no particular date), may be naive or aware regarding time zones, and always ignore leap seconds. They have five attributes: four read-only integers (hour
, minute
, second
, and microsecond
) and an optional tzinfo
(None
for naive instances).
time |
Instances of the class |
An instance t
of the class time
supplies the following methods:
isoformat |
Returns a string representing time |
replace |
Returns a new
|
strftime |
Returns a string representing time An instance |
Instances of the datetime
class represent an instant (a date, with a specific time of day within that date), may be naive or aware of time zones, and always ignore leap seconds. datetime
extends date
and adds time
’s attributes; its instances have read-only integers year
, month
, day
, hour
, minute
, second
, and microsecond
, and an optional tzinfo
(None
for naive instances).
Instances of datetime
support some arithmetic: the difference between datetime
instances (both aware, or both naive) is a timedelta
instance, and you can add or subtract a timedelta
instance to/from a datetime
instance to construct another datetime
instance. You can compare two instances of the datetime
class (the later one is greater) as long as they’re both aware or both naive.
datetime |
The class |
combine |
Returns a
|
fromordinal |
Returns a |
fromtimestamp |
Returns a |
now |
Returns a |
strptime |
Returns a |
today |
Returns a naive |
utcfromtimestamp |
Returns a naive |
utcnow |
Returns a naive |
An instance d
of datetime
also supplies the following methods:
Instances of the timedelta
class represent time intervals with three read-only integer attributes: days
, seconds
, and microseconds
.
The third-party pytz
module offers the best, simplest ways to create tzinfo
instances to make time zone–aware instances of the classes time
and datetime
. (pytz
is based on the Olson library of time zones. pytz
, like just about every third-party Python package, is available from PyPI: just pip install pytz
.)
The best way to program around the traps and pitfalls of time zones is to always use the UTC time zone internally, converting from other time zones on input, and to other time zones only for display purposes.
pytz
supplies the attributes common_timezones
, a list of over 400 strings that name the most common time zones you might want to use (mostly of the form continent
/
city
, with some synonyms like 'UTC'
and 'US/Pacific'
) and all_timezones
, a list of over 500 strings that also supply other synonyms for the time zones. For example, to specify the time zone of Lisbon, Portugal, by Olson library standards, the canonical way is 'Europe/Lisbon'
, and that is what you find in common_timezones
; however, you may also use 'Portugal'
, which you find only in all_timezones
. pytz
also supplies the attributes utc
and UTC
, two names for the same object: a tzinfo
instance representing Coordinated Universal Time (UTC).
pytz
also supplies two functions:
country_timezones |
Returns a list of time zone names corresponding to the country whose two-letter ISO code is |
timezone |
Returns an instance of For example, to print the Honolulu equivalent of midnight, December 31, 2005, in New York:
|
The third-party package dateutil
(which you can install with pip install python-dateutil
) offers modules to manipulate dates in many ways: time deltas, recurrence, time zones, Easter dates, and fuzzy parsing. (See the package’s website for complete documentation of its rich functionality.) dateutil
’s main modules are:
easter |
Returns the
prints |
parser |
Returns the
prints |
relativedelta |
You can call
Note that “next Monday,” by |
rrule |
Module |
An instance r
of the type rrule.rrule
supplies several methods:
after |
Returns the earliest |
before |
Returns the latest |
between |
Returns all For example, to say “once a week throughout January 2018,” the snippet:
prints: 2018-01-01 2018-01-08 2018-01-15 2018-01-22 2018-01-29 |
count |
Returns the number of occurrences of recurrence rule |
The sched
module implements an event scheduler, letting you easily deal, along a single thread of execution or in multithreaded environments, with events that may be scheduled in either a “real” or a “simulated” time scale. sched
supplies a scheduler
class:
scheduler |
The arguments
|
If monotonic time (time cannot go backward, even if the system clock is adjusted backward between calls, e.g., due to leap seconds) is important to your application, use v3 time.monotonic
for your scheduler. A scheduler
instance s
supplies the following methods:
cancel |
Removes an event from |
empty |
Returns |
enterabs |
Schedules a future event (a callback to
|
enter |
Like To schedule an event for repeated execution, use a little wrapper function; for example:
|
run |
Runs scheduled events. In v2, or if |
The calendar
module supplies calendar-related functions, including functions to print a text calendar for a given month or year. By default, calendar
takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday
. calendar
handles years in module time
’s range, typically (at least) 1970 to 2038.
python -m calendar
offers a useful command-line interface to the module’s functionality: run python -m calendar -h
to get a brief help message.
The calendar
module supplies the following functions: