1

I have the code below that returns the date in the following format: m/d/yyyy, but I would like it to return it as mm/dd/yy( So it would show a 0- before single digit dates and only show the last two digits of the year). How can I tweak it so?

import datetime
today = datetime.date.today()
'{0.month}/{0.day}/{0.year}'.format(today)
Samuel Dion-Girardeau
  • 2,790
  • 1
  • 29
  • 37
0004
  • 1,156
  • 1
  • 14
  • 49

3 Answers3

1

You're going to want to use strftime

datetime.date.today().strftime("%m/%d/%y")

You can find a list of directives here.

ollien
  • 4,418
  • 9
  • 35
  • 58
0
import datetime
today = datetime.date.today()
'{0:%m%d%y}'.format(today).format(today)

returns: '052818'

0004
  • 1,156
  • 1
  • 14
  • 49
0

Here is a sample program that gets you the output that you are seeking:

import datetime

now = datetime.datetime.now()

now = now.strftime('%m/%d/%y')
print(now)

We can use the strftime method to format the date. We pass the lowercase m (%m) because this will get return the month with a 0 in front of it. The lower case %d will also pass a day, and the lowercase %y will pass a year, only showing the last two digits as you specified

Here is your output:

05/28/18

And if you work with a day in the single digits, you get the 0 in front of the day that you wanted:

05/03/18
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27