Reputation: 136
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
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
Reputation: 8033
from datetime import datetime
today = datetime.today().strftime('%d%m%Y')
print(today)
Output
18092019
Upvotes: 0
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
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
Reputation: 356
You can do something like below.
from datetime import datetime
today = str(datetime.today().date())
Upvotes: 1