Skip to content
Advertisement

Why am I receiving this error? This date function has worked fine in my overall script until today

I am using this date function in a python script of mine and it has been working for months. Now, as of this morning it is not working. Here is an image of the error that I receive when I try and run the function. I receive the

error in script when running date function by itself.

date function that I’m using to format the date:

def format_date(date):
    return str(int(date[4:6]) + '/' + str(int(date[6::])) + '/' + date[0:4])

error that I receive after I try and run the function:

TypeError                                 Traceback (most recent call last)
<ipython-input-19-7b46987210f9> in <module>
----> 1 format_date(20220425)

<ipython-input-18-c708fe24a649> in format_date(date)
      1 def format_date(date):
----> 2     return str(int(date[4:6]) + '/' + str(int(date[6::])) + '/' + date[0:4])

TypeError: 'int' object is not subscriptable

Here is the error that I receive when I try and run the entire script without isolating the function.

    return str(int(date[4:6])) + '/' + str(int(date[6::])) + '/' + date[0:4]
ValueError: invalid literal for int() with base 10: ''

Advertisement

Answer

What you are doing is slicing an integer type formate_date(int)
that’s why you are getting an error.

Instead what you should do is to first convert your given parameter to string type.
which also makes your overall code look even cleaner.

def format_date(date):
    date = str(date)
    return date[4:6] + '/' + date[6::] + '/' + date[0:4]

#input formate_date(20220425)
#output 04/25/2022
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement