Difference Between Two datetimes

M.-A. Lemburg mal at egenix.com
Tue Dec 29 10:21:22 EST 2009


W. eWatson wrote:
> According to one web source, this program:
> 
> import datetime
> bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
> nat  = datetime.datetime(1973, 1, 18, 3, 45, 50)
> 
> difference = bree - nat
> print "There were", difference, "minutes between Nat and Bree"
> 
> yields:
> There were 3071 days, 0:49:35 minutes between Nat and Bree
> 
> That's fine, but I'd like to start with two dates as strings, as
> "1961/06/16 04:35:25" and "1973/01/18 03:45:50"
> 
> How do I get the strings into a shape that will accommodate a difference?
> 
> For example,
> t1=datetime.datetime.strptime("2009/01/02 13:01:15","%y/%m/%d %H:%M:%S")
> doesn't do it.
> ValueError: time data did not match format:  data=2009/01/02 13:01:15
> fmt=%y/%m/%d %H:%M:%S

Here's how you'd do this with mxDateTime:

http://www.egenix.com/products/python/mxBase/mxDateTime/

>>> from mx.DateTime import *
>>> bree = DateTimeFrom("1981/06/16 04:35:25")
>>> nat = DateTimeFrom("1973/01/18 03:45:50")
>>> bree
<mx.DateTime.DateTime object for '1981-06-16 04:35:25.00' at 2b99c7881088>
>>> nat
<mx.DateTime.DateTime object for '1973-01-18 03:45:50.00' at 2b99c6e342f0>

Now, let's look at the date/time difference:

>>> bree - nat
<mx.DateTime.DateTimeDelta object for '3071:00:49:35.00' at 2b99c6e36500>

i.e. 3071 days, 49 minutes, 35 seconds.

If you want a more human readable, relative format use Age():

>>> Age(bree, nat)
<RelativeDateTime instance for '(+0008)-(+04)-(+29) HH:(+49):(+35)' at 0x2b99c6e37ef0>

i.e. 8 years, 4 months, 29 days, 49 minutes, 35 seconds.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 29 2009)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::: Try our new mxODBC.Connect Python Database Interface for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/



More information about the Python-list mailing list