-1

I have the following function:

function(['28-02-2016','31-02-2016'])
['february', '*']

EDIT (full function)

import calendar
def function(monthList):
    months = {"01": "january", "02":"february", "03":"march", "04":"april", "05":"may", "06":"june", "07":"july", "08":"august", "09":"september", "10":"october", "11":"november", "12":"december"}
    returnList = []
    for monthStr in monthList:
            month = str(monthStr)[3:5]
    if month in months.keys():
        if int(monthStr[:2]) <= calendar.monthrange(int(monthStr[-4:]), int(monthStr[3:5]))[1]:
            returnList.append(months[month])
        else:
            returnList.append("*")
    else:
        returnList.append("*")
return returnList

If the date is right, the function creates a list where the month is put, otherwise a '*' is put. But if I write:

function([02-02-20a1]:

I get this error:

     6         month = str(monthStr)[3:5]
     7         if month in months.keys():
---> 8             if int(monthStr[:2]) <= calendar.monthrange(int(monthStr[-4:]), int(monthStr[3:5]))[1]:
     9                 returnList.append(months[month])
    10             else:

ValueError: invalid literal for int() with base 10: '20a1'

So Python is telling me I have to put a control in the list number 8. How do I manage to tell the function to act like this?

function(['02-02-19a1'])
[*]
Vibes
  • 13
  • 4
  • It's telling you that `'20a1'` isn't a valid integer literal. If you get a `ValueError` you can assume it's not a valid date, so see https://docs.python.org/3/tutorial/errors.html for error handling. Also, you can simplify significantly with `datetime`'s built-in parsing, which will deal correctly with e.g. leap years. – jonrsharpe Oct 22 '16 at 21:09
  • 1
    Python tells that you have error in your code / input – agg3l Oct 22 '16 at 21:10
  • I have no idea what you mean by "controls". Clearly though "20a1" and "19a1" are not valid values to pass to `int`. – Daniel Roseman Oct 22 '16 at 21:10
  • 2
    *"Python is telling me I have to put a control in the list number 8"* - No. Where did you get that idea from? It is just telling you that `'20a1'` is not an integer. You should catch that exception and return `'*'`. I can't really give you a more specific answer because you did not show the whole function. – zvone Oct 22 '16 at 21:10
  • @DanielRoseman int(*, base=10) you wanted to say – agg3l Oct 22 '16 at 21:11
  • I am pretty sure there are better ways then what you use in the function, but since we cannot see the full function, the general idea is that a try/except should do the job. – Jacob Vlijm Oct 22 '16 at 21:11
  • Your code assumes that the `str(monthStr)` string is composed entirely of digits and hyphens in certain positions. Which is obviously not true for `'02-02-19a1'`. You need to check the format in advance (and not try to parse it if it's wrong) _or_ add `try/except` around statements that can fail and handle the cases where the assumption was wrong. – martineau Oct 22 '16 at 23:51
  • i added the text of the function further clarification guys, meanwhile thanks you guys for have been helping me :) – Vibes Oct 23 '16 at 08:31

1 Answers1

0

Use Python time.strptime and time.strftime:

import time

def get_month(date_string):
    try:
        t = time.strptime(date_string,'%d-%m-%Y')
        return time.strftime('%B', t).lower()
    except ValueError:
        return '*'

If the date is invalid, ValueError will be raised, in which case you return '*'.

Call get_month for each date string in your function.

def get_months(date_strings):
    return [get_month(date_string) for date_string in date_strings]
xli
  • 1,298
  • 1
  • 9
  • 30
  • That would not cover e.g. `function(['bla-7-99', 'iiiiiiiiiii'])` – zvone Oct 22 '16 at 21:13
  • Edited to use `strftime` and `strptime` instead. – xli Oct 22 '16 at 21:46
  • so i just have to add this little paragraph to the test of my function? – Vibes Oct 23 '16 at 08:30
  • @xli what if i wanted to add a list of potential dates as an input? – Vibes Oct 23 '16 at 12:53
  • You can add this function to your module. In your other function, call `get_month` for each potential date in the list, and add each result to a list, which you then return. More concisely, `return [get_month(monthStr) for monthStr in monthList]` – xli Oct 23 '16 at 14:39
  • get_month(['02-02-10a1','02-02-1992']) – Vibes Oct 23 '16 at 14:49
  • strptime() argument 0 must be str, not the function still doesn't allow me to put a list as an input – Vibes Oct 23 '16 at 14:50
  • I mean add a function `get_months` with definition `return [get_month(monthStr) for monthStr in monthList]` – xli Oct 23 '16 at 14:50
  • it works perfectly , thanks :) curiosity: is it possible to return februar (february into german) instead of february? – Vibes Oct 23 '16 at 16:12
  • @Vibes You can set the locale as shown [here](http://stackoverflow.com/a/985517/1231717). If the answer worked for you, you can accept it by clicking the check mark to the left of the answer. – xli Oct 23 '16 at 16:39