Qiao Li
Qiao Li

Reputation: 41

python error: can only concatenate str (not "datetime.timedelta") to str

i am trying to get the weeks between two dates and split into rows by week and here is the error message i got:

can only concatenate str (not "datetime.timedelta") to str Can anyone help on this one? thanks!!!

import datetime
import pandas as pd


df=pd.read_csv(r'C:\Users\xx.csv')
print(df)

# Convert dtaframe to dates
df['Start Date'] = pd.to_datetime(df['start_date'])
df['End Date'] = pd.to_datetime(df['end_date'])

df_out = pd.DataFrame()

week = 7

# Iterate over dataframe rows

for index, row in df.iterrows():
    date = row["start_date"]
    date_end = row["end_date"]
    dealtype = row["deal_type"]
    ppg = row["PPG"]
    # Get the weeks for the row
    while date < date_end:
        date_next = date + datetime.timedelta(week - 1)
        df_out = df_out.append([[dealtype, ppg, date, date_next]])
        date = date_next + datetime.timedelta(1)

# Remove extra index and assign columns as original dataframe

df_out = df_out.reset_index(drop=True)
df_out.columns = df.columns
df.to_csv(r'C:\Users\Output.csv', index=None)

Upvotes: 4

Views: 12515

Answers (2)

user13587121
user13587121

Reputation:

date is a Timestamp object which is later converted to a datetime.timedelta object.

datetime.timedelta(week - 1) is a datetime.timedelta object.

Both of these objects can be converted to a string by using str().

If you want to concatenate the string, simply wrap it with str()

date_next = str(date) + str(datetime.timedelta(week - 1))

Upvotes: 2

Tim Roberts
Tim Roberts

Reputation: 54678

You converted the start_date and end_date column to datetime, but you added the converted columns as Start Date and End Date. Then, in the loop, you fetch row["start_date"], which is still a string. If you want to REPLACE the start_date column, then don't give it a new name. Spelling matters.

Upvotes: 1

Related Questions