confused on calculating date difference in days.

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Oct 16 03:45:04 EDT 2007


"krishnakant Mane" <researchbase at gmail.com> writes:

> firstly, I can't get a way to convert a string like "1/2/2005" in a
> genuan date object which is needed for calculation.

Until recently, this was a wart in the Python standard library:
datetime objects exist in the 'datetime' module, but parsing strings
to get date/time components was only available in the 'time' module.

In Python 2.5, though, we have 'datetime.datetime.strptime'
<URL:http://docs.python.org/lib/datetime-datetime.html#l2h-634>, which
parses a string according to a specified format, and returns the
corresponding datetime value.

    >>> import datetime
    >>> datetime.datetime.strptime("2007-10-16t17:40:00", "%Y-%m-%dt%H:%M:%S")
    datetime.datetime(2007, 10, 16, 17, 40)

> now once this is done I will create a another date object with
> today = datetime.datetime.now()
> and then see the difference between this today and the string that I
> converted to date.

That's simple: datetime objects support difference via the subtraction
arithmetic operator, returning a datetime.timedelta instance
<URL:http://docs.python.org/lib/datetime-timedelta.html>.

    >>> value = datetime.datetime(2007, 10, 16, 15, 30, 45)
    >>> value - datetime.datetime(2007, 10, 16, 15, 20, 00)
    datetime.timedelta(0, 645)
    >>> value - datetime.datetime(2007, 10, 12, 8, 25, 19)
    datetime.timedelta(4, 25526)
    >>> value - datetime.datetime(2007, 11, 26, 0, 0, 0)
    datetime.timedelta(-41, 55845)

-- 
 \             "Experience is that marvelous thing that enables you to |
  `\      recognize a mistake when you make it again."  -- Franklin P. |
_o__)                                                            Jones |
Ben Finney



More information about the Python-list mailing list