MCS 260 Fall 2021
Emily Dumas
Python's time
module can tell you the current timestamp, i.e. the time in second since a certain base point, the epoch. It can also do some other things.
The epoch is usually 0:00 on January 1, 1970 (GMT), but officially it can be different in each Python installation.
time.time()
— return current timestamp (float).time.gmtime(0)
— return some data about the epoch for this Python installation.
time.sleep(seconds)
— pause execution for seconds
seconds.(The time
module has many other functions.)
The main thing I think the time
module is good for is measuring the elapsed time between two events, e.g.
import time
t0 = time.time()
for x in huge_list:
complicated_function(x)
t1 = time.time()
print("That took {:.2f} seconds".format(t1-t0))
Keep in mind this measures "wall clock" time, not the total CPU time spent doing actual work.
Module includes class datetime.datetime
for representing a Gregorian calendar time as month, day, hour, minute, second, microsecond.
datetime.datetime.now()
— The current local time (as reported by the OS)datetime.datetime.utcnow()
— The current time in UTC (equal to GMT)datetime.datetime(2021,8,23,10,3,27)
— object representing 27 seconds after 10:03am on Aug 23, 2021There are also datetime.date
objects, representing dates in the Gregorian calendar, and datetime.time
objects, representing a time of day.
These have similar behavior, so we will focus on datetime.datetime
.
Everything we've covered so far uses naive datetime objects, not labeled by a specific time zone.
Real world applications typically need to account for time zones (and their complexity).
We won't cover this in MCS 260 but I want to suggest:
The datetime module can take a string and convert it to a datetime object, which is one of its most powerful features.
datetime.datetime.strptime(date_string,format)
— Convert a string to a datetime, assuming it uses the format described in format
(%
-codes indicate datetime parts).datetime.datetime.strptime("2021-12-03","%Y-%m-%d")
— Parse a year-month-day string and make a datetime object out of it.Format codes for strptime
include (see full list):
%Y
= year%m
= month (two digit)%B
= full month name%d
= day (two digit)%A
= weekday name (e.g. Friday)%a
= weekday abbreviation (e.g. Fri)%H
= hour (two digit, 24 hour format)%I
= hour (two digit, 12 hour format)%M
= minute (two digit)%S
= second%p
= AM/PMIf dt
is a datetime object:
dt.strftime(format)
— converts dt
to a string in the given format.If dt
is a datetime object:
datetime.datetime.fromtimestamp(ts)
— Convert from a timestamp to a local date and timedt.timestamp()
— Convert from datetime to a timestampFor datetime objects, the comparison operator <
means "is earlier in time than".
datetime.datetime(1999,11,19) < datetime.datetime.now() # True!
Subtracting two datetime objects gives a datetime.timedelta
object.
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
— build a new timedelta objectdelta.total_seconds()
— convert an existing timedelta object to units of secondsInternally, timedelta stores days, seconds, and microseconds. It supports division by other timedelta objects, and multiplication/division by numbers.
dateutil
is another module not in the standard library that is often used for handling dates and times in Python.
(Ask pip to install python-dateutil
.)
A nice feature of dateutil
is that it has a function dateutil.parser.parse(s)
to make a "best guess" at the meaning of a date string s
of unknown format.
Not required in MCS 260.