Eshu Manohare
Eshu Manohare

Reputation: 43

Convert datetime string in list to datetime object

Line 84 in lstToDt() method, I tried to convert 'i' which takes a string datetime from list to datetime object but:

Code :

def lstToDt(lt):      # Converts list string elements into Dates
    for i in lt:
        i = datetime.datetime.strftime(i,"%Y-%m-%d")
        lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
    return lt

Errors :
i = datetime.datetime.strftime(i,"%Y-%m-%d")
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
TypeError: strptime() argument 1 must be str, not datetime.datetime

What is happening? Can anyone help please?

Upvotes: 0

Views: 65

Answers (1)

Harshit verma
Harshit verma

Reputation: 548

You have passed string value to strptime, that is not acceptable for python,

def lstToDt(lt):      # Converts list string elements into Dates
    for i in lt:
        j = datetime.datetime.strptime(i,"%Y-%m-%d")
        lt.append(datetime.datetime.strptime(j,"%Y-%m-%d"))
    return lt

This should work! Hope this helps!

Upvotes: 1

Related Questions