Home > other >  How to handle a list which contains elements having leading zeros?
How to handle a list which contains elements having leading zeros?

Time:09-09

I have a data which is coming from another source in the form of a nested list which looks as below:

data = [
    ["store1", 50, 02132020], 
    ["store2", 20, 02112020], 
    ["store3", 25, 02172020]
]

Here, 50 is the price.

And, 02152022 is the date.

When, I print the data, I get below error:

leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

How to deal with list whose elements may contain "leading zeros"?

CodePudding user response:

My suggestion is that you may cast the third element in the list into string, then using datetime to cast into datetime object since it's a date.

I don't know the exact source of data. Firstly, It cannot be a vanilla python list object since it cannot pass interpreter check. Secondly, It also maked nonsense as a JSON object. Something like 02132020 are not allowed to appear in JSON.

CodePudding user response:

import datetime

data = [
    ["store1", 50, "02132020"], 
    ["store2", 20, "02112020"], 
    ["store3", 25, "02172020"]
]

for i in data:
    print({
        "store_name" : i[0],
        "price": i[1],
        "date":(datetime.datetime.strptime(i[2], '%m%d%Y')).date()
    })

Output:

{'store_name': 'store1', 'price': 50, 'date': datetime.date(2020, 2, 13)}
{'store_name': 'store2', 'price': 20, 'date': datetime.date(2020, 2, 11)}
{'store_name': 'store3', 'price': 25, 'date': datetime.date(2020, 2, 17)}
  • Related