I want my code to print the date like this:
from datetime import datetime
now = datetime.now()
print now.day + "/" now.month + "/" + now.year
But the compiler says "/" is an invalid syntax.
What's wrong with my code?
You forgot one +
before now.month
:
print now.day + "/" + now.month + "/" + now.year
And then you will see that you have to cast now.xxx
to string:
>>> print str(now.day) + "/" + str(now.month) + "/" + str(now.year)
30/12/2014
You might also want to use the strftime
to format dates:
>>> print now.strftime('%d/%m/%Y')
30/12/2014
You need a +
before now.month
and also you need to convert all the now.
to strings.
>>> print str(now.day) + "/" + str(now.month) + "/" + str(now.year)
30/12/2014
You can try this also
import datetime
print datetime.strftime("%d/%m/%Y")
You can Check Here for more details.
As other's have already mention you need a +
before now.month
. But you can use format
to make the answer look better
print "{}/{}/{}".format(now.day,now.month,now.year)
Always use format for concatenating strings.
You are tying to concatenate sting with int in your print statement. That is why your code doesn't work. But if you want to use your code you must do this way.
from datetime import datetime
now = datetime.now()
print now.day,"/",now.month,"/",now.year
otherwise, use the options that are offered here.