Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)
like image 468
Qiao Li Avatar asked Oct 19 '25 03:10

Qiao Li


2 Answers

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))

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.

like image 39
Tim Roberts Avatar answered Oct 21 '25 18:10

Tim Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!