how to calc the difference between two datetimes?

Jp Calderone exarkun at divmod.com
Sun May 8 21:11:41 EDT 2005


On Sun, 8 May 2005 19:06:31 -0600, Stewart Midwinter <stewart.midwinter at gmail.com> wrote:
>After an hour of research, I'm more confused than ever. I don't know
>if I should use the time module, or the eGenix datetime module. Here's
>what I want to do:  I want to calculate the time difference (in
>seconds would be okay, or minutes), between two date-time strings.
>
>so: something like this:
>time0 = "2005-05-06 23:03:44"
>time1 = "2005-05-07 03:03:44"
>
>timedelta = someFunction(time0,time1)
>print 'time difference is %s seconds' % timedelta.
>
>Which function should I use?

  The builtin datetime module:

    >>> import datetime
    >>> x = datetime.datetime(2005, 5, 6, 23, 3, 44)
    >>> y = datetime.datetime(2005, 5, 8, 3, 3, 44)
    >>> x - y
    datetime.timedelta(-2, 72000)
    >>> y - x
    datetime.timedelta(1, 14400)
    >>> 

  Parsing the time string is left as an exercise for the reader (hint: see the time module's strptime function).

  Jp



More information about the Python-list mailing list