Subtracting two dates in python

John Gordon gordon at panix.com
Thu Jul 31 18:31:11 CEST 2014


In <ea9aa6cd-1fe4-420e-ac11-c3ff2be3befa at googlegroups.com> eshwar080 at gmail.com writes:

> I would like to subtract two dates

> i.e I have entered a date into a textbox which is of type String like below

> type(waitForObject(":VWAP Calculator_LCDateTextField"), "07/24/14")

> I am capturing that date like below

> Current = (waitForObject(":VWAP Calculator_LCDateTextField").text)

> so, now I want to subtract the captured date with my current system date and get the difference in days. I tried many ways and see no success. Someone please help with this as soon as possible.

> P.S: I have python 2.4 and 2.7

If you have the user-entered date in a string format, you can use
datetime.strptime() to convert it into a datetime object, like so:

    from datetime import datetime
    user_date = datetime.strptime(user_input, "%m/%d/%y")

Get the current system date like this:

    now_date = datetime.now()

Subtract the two datetime objects to obtain a timedelta object:

    mydelta = now_date - user_date

Look at the days attribute to get the difference in days:

   mydelta.days

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list