0

My code looks like this

import csv
import datetime

now = datetime.datetime.now()
month_year = (now.month, now.year)
print(month_year)

outputfilename = 'Filename'+month_year+'.csv'
print(outputfilename)

print(month_year) gets me my month year

(11, 2019)

and I would like the date to be in my filename however

outputfilename = 'Filename'+month_year+'.csv'
print(outputfilename)

gives me the following error

    outputfilename = 'Filename'+month_year+'.csv'
TypeError: must be str, not tuple

Any suggestions please?

5 Answers 5

1

In the line:
month_year = (now.month, now.year),
you declared the variable month_year as a tuple and not string (as the exception says).

Change the line to this: month_year = now.month

Sign up to request clarification or add additional context in comments.

Comments

1

The error actually explains it: you can't concatenate string with tuple object (monthyear is a tuple here). If you want it to be as something like Filename(11, 2019).csv, you can do it with: outputfilename = 'Filename' + str(month_year) +'.csv'.

But there are many nice naming options instead of Filename(11, 2019).csv. We can help you if you provide the exact output you want.

Comments

1

In python, you can only use string type with "plus". So I suggest you to change your code to the following format.

import csv
import datetime
now = datetime.datetime.now()
month_year = (now.month, now.year)
print(month_year)
outputfilename = 'Filename'+'_'+str(month_year[0])+'_' + str(month_year[1]) + '.csv'
print(outputfilename)

Comments

1

You can use like this month_year = str(now.month) +"_" + str(now.year) and your filename will be Filename_11_2019.csv.

Comments

1

You cannot print tuple/list/int+str so you need to convert your month_year variable into string to be able to use it:

month_year = str((now.month, now.year))

This would give:

'(11, 2019)'

Comments

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.