0

I have a function that will convert 3 numbers into a date.

def conv(month, day, year):
    months = ('None','January','February','March','April','May','June','July','August','September','October','November','December')
    print(months[month],str(day)+',',year)

so if I run the function like this: conv(6,17,2016) the output will be:

June 17, 2016

so far so good, but what if I give 06 for the month instead of 6 how can I get the same output like above? is there any way to use 06 and somehow turning it into 6 for indexing or I have to only give 6 and there is no way for doing that?

Ghost.007
  • 35
  • 4
  • 4
    Is there a reason you're not using the `datetime` module? It has the facility to deal with zero-padded values, see [here](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) – roganjosh Aug 30 '18 at 09:15
  • 06 would be invalid - it'd throw an error – Dr G. Aug 30 '18 at 09:17
  • yeah I know I can use datetime but I just wondering if there is a way for that indexing – Ghost.007 Aug 30 '18 at 09:21

5 Answers5

1

assuming you are aware that 06 will automatically raise a syntax error, that means you can only create a string such as "06".

with that said, simple use to convert to int

number = int(month)
Wong Siwei
  • 115
  • 2
  • 6
1

I would suggest to use datetime,

In [31]: d = datetime.datetime.now().date()

In [32]: d.strftime('%B %d, %Y')
Out[32]: 'August 30, 2018'

Or use calender.

import calendar
def conv(month, day, year):
    print(calendar.month_name[int(month)],str(day)+',',year)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
1

This will be a little easier to digest:

import datetime

def conv(month, day, year):
    d = datetime.date(year, month, day)
    print(d.strftime("%B %d, %Y"))
Dr G.
  • 1,298
  • 9
  • 17
0

cast your 06 to int - it will then be a normal 6. So you will print by using print(months[int(month)],str(day)+',',year)

but as mentioned in the comments - just use datetime module instead :-)

Cut7er
  • 1,209
  • 9
  • 24
0

You can convert tuple to datetime then use .strftime to format it:

>>> tup=(2018,8,30)
>>> from datetime import datetime
>>> datetime(*tup)
datetime.datetime(2018, 8, 30, 0, 0)
>>> print(datetime(*tup)) # print
2018-08-30 00:00:00
>>> datetime(*tup).strftime('%B %d, %y')
'August 30, 18'
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114