smaxx1337
smaxx1337

Reputation: 136

TypeError: must be str, not datetime.date when trying to create a file in Python

I am trying to generate a text file that looks like this:

config_18092019_123456.txt

So I thought this line in Python will do it:

file = open("config_" + today + "_" + choosen_asn + ".txt","w+", encoding='utf-8')

But I get following error:

Traceback (most recent call last):
  File "wes-prefix.py", line 15, in <module>
    file = open("config_" + today + "_" + choosen_asn,"w+", encoding='utf-8')
TypeError: must be str, not datetime.date

The variable today looks like this:

today = date.today()

How do I fix this? How do I get the current date as string?

Upvotes: 3

Views: 4523

Answers (6)

Naveen soni
Naveen soni

Reputation: 21

Try to convert date to string using str(today).

Upvotes: 0

Milad
Milad

Reputation: 473

You should convert date to string:

today = date.today()
dateStr = today.strftime("%d%m%Y")
file = open("config_" + today + "_" + choosen_asn + ".txt","w+", encoding='utf-8')

Upvotes: 0

moys
moys

Reputation: 8033

from datetime import datetime
today = datetime.today().strftime('%d%m%Y')
print(today)

Output

18092019

Upvotes: 0

Bogdan Doicin
Bogdan Doicin

Reputation: 2416

Convert today's date to string. The full code is this:

from datetime import date

choosen_asn='123456'

today = date.today()
file = open("config_" + str(today) + "_" + choosen_asn + ".txt","w+", encoding='utf-8')

Upvotes: 0

el_oso
el_oso

Reputation: 1061

you need to explicitly cast to string type

today_as_string = str(date.today())

you can check types like this:

type(today)
type(today_as_string)

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 356

You can do something like below.

from datetime import datetime
today = str(datetime.today().date())

Upvotes: 1

Related Questions