Brother85
Brother85

Reputation: 71

Subtracting two dates in Python

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

Upvotes: 3

Views: 6397

Answers (2)

user2497586
user2497586

Reputation:

Try something like this:

>>> from datetime import datetime
>>> x = datetime.strptime("07/24/14", "%m/%d/%y")
>>> y = datetime.strptime("07/30/14", "%m/%d/%y")
>>> x-y
datetime.timedelta(-6)
>>> (x-y).days
-6

This uses the datetime.strptime method of converting a string to a datetime object. Then you can simply do arithmetic on datetime objects. The result will be in a timedelta (basically a difference of time) which you can then call .days on if you want the difference to be in days. You can read about all these functions here.

If you want to get current date using these methods, it's as simple as:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2014, 7, 31, 12, 16, 12, 966428)

And it returns another datetime object which you can then perform the date arithmetic on.

Upvotes: 5

Imran
Imran

Reputation: 90999

  1. Parse the string to datetime objects (Converting string into datetime)

  2. Subtract the datetime objects, you'll get a timedelta object which has days property

delta = dtend - dtstart
print delta.days

Upvotes: 0

Related Questions