time module vs. datetime module: plain language for beginners

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Mar 25 19:36:44 EDT 2015


On Thu, 26 Mar 2015 08:16 am, Jinghui Niu wrote:

> I am learning python programming. One thing that gives me a lot of
> confusion is the division of labours between the time module and the
> datetime module.
> 
> As it turns out to be, time module is not only about time, it's about date
> too. And datetime doesn't natively support timezone, you have to create 
> one for yourself.
> 
> Why duplicate datetime module? What is the design rationale between this
> division? Can't we just have one unified module that deals with dates and
> times? Could someone please list some situations where the two modules are
> actually useful in their own ways respectively?
> 
> Explanation with not too much jargon is highly appreciated. Thanks in
> advance.

The time module is written in C, and is mostly interface to low-level
operating system functions. The datetime module is written in Python. It
would be painful to write the time module in Python, or the datetime module
in C, so they are separate.

py> import time
py> import datetime
py> time.__file__
'/usr/local/lib/python3.3/lib-dynload/time.cpython-33m.so'
py> datetime.__file__
'/usr/local/lib/python3.3/datetime.py'


There are other designs possible. For example, the datetime module could be
written in Python, and it could import an accelerator module for the C
parts:

    from _datetime import *


In fact, it already does that! But the private accelerator C datetime
doesn't include the contents of time, so there are still two public
modules.

Why didn't the time functions just get moved into _datetime? As with most of
these things, the answer is probably for historical reasons. You would need
to look far back in the history of Python to see how those two modules
evolved over the years, but my guess is that the very first version of each
had no overlap, and the overlap has just developed since then.

The oldest version of Python I have is version 1.5, and it has a time module
but no datetime module. So my guess is that time was written first, as an
interface to the operating system time routines, in C. Then, some versions
later, a pure-Python datetime module was added, and then later still an
accelerated C _datetime module was added. That's my guess.

I cannot remember the last time I have needed to import both time and
datetime from the same module. I usually only import one, or the other. For
example, I might do:

time.sleep(3)

which doesn't require the datetime module.


-- 
Steven




More information about the Python-list mailing list