Difference Between Two datetimes

Ben Finney ben+python at benfinney.id.au
Mon Dec 28 07:50:30 EST 2009


"W. eWatson" <wolftracks at invalid.com> writes:

> Lie Ryan wrote:
> > what's strange about it? the difference between 2009/01/02 13:01:15
> > and 2009/01/04 13:01:15 is indeed 2 days... Can you elaborate what
> > do you mean by 'strange'?

> Easily. In one case, it produces a one argument funcion, and the other
> 2, possibly even a year if that differs.

In both cases it produces not a function, but a ‘datetime.timedelta’
object::

    >>> import datetime
    >>> t1 = datetime.datetime(2009, 1, 2, 13, 1, 15)
    >>> t2 = datetime.datetime(2009, 1, 4, 13, 1, 15)
    >>> type(t1)
    <type 'datetime.datetime'>
    >>> type(t2)
    <type 'datetime.datetime'>

    >>> dt = (t2 - t1)
    >>> type(dt)
    <type 'datetime.timedelta'>

What you're seeing in the interactive interpreter is a string
representation of the object::

    >>> dt
    datetime.timedelta(2)

This is no different from what's going on with any other string
representation. The representation is not the value.

> How does one "unload" this structure to get the seconds and days?

It's customary to consult the documentation for questions like that
<URL:http://docs.python.org/library/datetime.html#datetime.timedelta>.

> To find the difference more clearly. Why not just return (0,2,3555)

Because the ‘datetime.timedelta’ type is more flexible than a tuple, and
has named attributes as documented at the above URL::

    >>> dt.days
    2
    >>> dt.seconds
    0
    >>> dt.microseconds
    0

-- 
 \        “If you have the facts on your side, pound the facts. If you |
  `\     have the law on your side, pound the law. If you have neither |
_o__)                       on your side, pound the table.” —anonymous |
Ben Finney



More information about the Python-list mailing list