0

I am trying to add zeroes to a date if the day/month is less than 10.

For example, if 2/12/200 is entered, convert it to 02/12/2000.

userDate = input("What is the date? Please enter in MM/DD/YYYY format")

newDate = ''
newDate = userDate[3:5]+ "."+userDate[0:2]+"."+ userDate[6:]
print (newDate)
Josh Withee
  • 9,922
  • 3
  • 44
  • 62
SeeMorton
  • 41
  • 3

3 Answers3

0

You will need to split the userDate on / rather slice it, e.g.:

m, d, y = userDate.split('/')

It pretty easy to left fill, and it is covered in the linked duplicate, here's one way:

m = m.zfill(2)       # 02
d = d.zfill(2)       # 12

Padding to the right is slightly different:

y = y.ljust(4, '0')  # 2000

You can then join() them back up:

newDate = '/'.join([d, m, y])

You can do this all in one line using str.format() and the formatting mini language, e.g.:

newDate = '{:>02s}/{:>02s}/{:<04s}'.format(*userDate.split('/'))  # 02/12/2000
AChampion
  • 29,683
  • 4
  • 59
  • 75
0
new_date = "/".join([i.zfill(2) for idx, i in enumerate(userDate.split("/"))])
AdriVelaz
  • 543
  • 4
  • 15
0
>>> userDate = str(input("What is the date? Please enter in MM/DD/YYYY format"))
What is the date? Please enter in MM/DD/YYYY format'2/12/200'
>>> m,d,y = userDate.split('/')
>>> m = m.zfill(2)           # For Left padding
>>> d = d.zfill(2)           # For Left padding
>>> y = y.ljust(4, '0')      # For Right padding
>>> print """%s/%s/%s""" % (m,d,y)
02/12/2000
>>> 
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86