Python Forum
Subtracting datetimes [index]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subtracting datetimes [index]
#1
Hi all,

When I download stock data from Yahoo! Finance, it comes in a dataframe with datetime index. What I'm ultimately trying to do here is add buy and sell dates to lists and then subtract them to get duration.

I have a df with column 'Signal' that says 'Yes' if I should buy. Then:

BuyDates = []
SellDates = []

for i in range(len(df)-11):
    if df.Signal.iloc[i]:
        BuyDates.append(df.iloc[i+1].name)
        for j in range(1,11):
            if df['RSI'].iloc[i+j]>40:
                SellDates.append(df.iloc[i+j+1].name)
                break
#            elif j==10:
            elif df.iloc[i+j+1].name - df.iloc[i].name > 10: #if next trading day is more than 10 days from start, then 
                SellDates.append(df.iloc[i+j].name)
The trade should be up to 10 days long so lines 12-13 are trying to say if tomorrow's date-- (i + j + 1).name --minus start date (i) is greater than 10, append today's date-- (i + j).name --to list SellDates. Line 12 gets: TypeError: '>' not supported between instances of 'Timedelta' and 'int'

In my debugging effort, I tried this:
for i in range(len(BuyDates)):
    print(BuyDates[i],'-------',SellDates[i],'-------',SellDates[i]-BuyDates[i])
That worked! type(SellDates[i]) also comes back as a timestamp, which is what the datetime index is.

So... why can I subtract dates in the latter case but not in the former?

Thanks!
Reply
#2
It's not the subtraction that's the problem, it's the comparison.

You may know you want the 10 to represent 10 days, but python doesn't. Maybe you want 10 hours or 10 seconds.

You need to compare it with a Timedelta object that represents 10 days.

>>> a = datetime.now()
>>> b = datetime.now()
>>> b - a
datetime.timedelta(seconds=5, microseconds=439115)
>>> b - a > 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'
>>> b - a > timedelta(seconds=5)
True
Reply
#3
you might also be interested in: https://pymotw.com/3/datetime/#timedeltas
Mark17 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with subtracting values using SQLite & Python Extra 10 3,414 May-10-2022, 08:36 AM
Last Post: ibreeden
  Indexing problem while iterating list and subtracting lbtdne 2 2,138 May-14-2020, 10:19 PM
Last Post: deanhystad
  Subtracting values between two dictionaries/ floating point numbers FloppyPoppy 5 5,925 Mar-04-2019, 01:00 PM
Last Post: snippsat
  Subtracting gives a keyerror: xepicxmonkeyx 7 16,625 Oct-03-2016, 04:12 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020