3

Two columns in a csv file as below. I want to check the date intervals of each,

i.e.

'2013-11-01' - '2013-10-08',

'2013-12-02' - '2013-11-01' etc.

enter image description here

After,

df = pd.read_csv(f, sep='\t')
df_date = df["Date"]

I tried:

print (df["Date"].shift(-1) - df["Date"]).astype('timedelta64[d]')

and

print df['Date'].shift() - df['Date']

both of them returned:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

What went wrong, and how can I correct it? Thank you.

1
  • 1
    Have you tried converting the columns to datetime before taking the difference? Commented Aug 9, 2019 at 7:23

1 Answer 1

2

Problem is column Date is filled string repr of datetimes, so first is necessary converting - e.g. by parse_dates parameter or to_datetime, then call Series.diff:

df = pd.read_csv(f, sep='\t', parse_dates=['Date'])

print (df["Date"].diff(-1))

Another solution:

df = pd.read_csv(f, sep='\t')
df["Date"] = pd.to_datetime(df["Date"])
print (df["Date"].diff(-1))
Sign up to request clarification or add additional context in comments.

1 Comment

hope you are very well. thank you for the lightening speed solution, and sharing of knowledge!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.