Home > Net >  Python String with date.today() returning with TypeError
Python String with date.today() returning with TypeError

Time:07-05

I'm sorry if this question is very simple. I'm new to Python and more often than not this website can answer my questions, but this time I don't even know how to search for it.

Essentially, the part of my code that is not working is the following:

from datetime import date
today = date.today()

startinput = today   "T"
print(startinput)

So I want to retrieve the result

2022-07-04T 

OBS: This is the current date as I write this question, so I want it to keep returning YYYY-MM-DDT

But I get the error

TypeError: unsupported operand type(s) for  : 'datetime.date' and 'str'

Can anyone please help me out? Or point me to somewhere where I can find answers?

Many thanks!

CodePudding user response:

Convert date.today() to a str before you try to add another str to it:

>>> from datetime import date
>>> str(date.today())   "T"
'2022-07-04T'

or put it in an f-string, which will convert it to a str automatically:

>>> f"{date.today()}T"
'2022-07-04T'

CodePudding user response:

You can customise the date format when converting a datetime object to a string object

from datetime import date

today = date.today().strftime("%Y-%m-%dT")
print(today)

# 2022-07-05T

CodePudding user response:

You can do this:

from datetime import date

today = str(date.today())   "T"

print(today)

# 2022-07-05T
  • Related