-1

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?

fredtantini
  • 15,966
  • 8
  • 49
  • 55
Rikas
  • 187
  • 7
  • 15

5 Answers5

1

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
fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

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
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You can try this also

import datetime
print datetime.strftime("%d/%m/%Y")

You can Check Here for more details.

Community
  • 1
  • 1
Himanshu
  • 4,327
  • 16
  • 31
  • 39
0

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

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.