-1

I have a list of dates that gets imported as strings. I've tried a bunch of different things to convert it to a list of dates. Doesn't matter how I do it I get an error.

#import valid dates from map file as list
valdts = dfmap.loc[row, 'valdata'].split(', ')
print(valdts)
>>
['1/1/1990', '6/6/1990', '7/4/1776']

#convert strings to dates
attempt1:
valdts = [d.strftime('%Y-%m-%d') for d in valdts]
>>
AttributeError: 'str' object has no attribute 'strftime'

attempt2:
a = [date_obj.strftime('%Y%m%d') for date_obj in valdts]
>>
AttributeError: 'str' object has no attribute 'strftime'

attempt3:
a = datetime.strptime(valdts, '%d %b %Y')
>>
TypeError: strptime() argument 1 must be str, not list

attempt4:
a = valdts.sort(key = lambda dt: datetime.strptime(dt, '%d %m %Y'))
>>
ValueError: time data '1/1/1990' does not match format '%d %m %Y'

attempt5:
for dt in valdts:
    dt = dt.replace('/',',')
    print(dt)
    c = datetime.strptime('.'.join(str(i) for i in dt).zfill(8), "%Y.%m.%d")
>>
'1,1,1990'
ValueError: time data '1.,.1.,.1.9.9.0' does not match format '%Y.%m.%d'

attempt6:
for dt in valdts:
    dt = dt.replace('/',',')
    datetime.strptime(dt, '%d %m %Y')
>>
ValueError: time data '1,1,1990' does not match format '%d %m %Y'

I'm getting quite frustrated. The different approaches above are based on responses to similar but not quite the same questions posted by others. The question most similar to mine has been downvoted. Am I trying to do something stupid? Would really appreciate some help here. Thanks.

Note: datetime.datetime gives me an error. AttributeError: type object 'datetime.datetime' has no attribute 'datetime' but just datetime works for other parts of my code.

SModi
  • 125
  • 14
  • Could you please provide a data sample? Looks like you're working with pandas dataframe / series, so it might be better to use (vectorized) pandas methods. – FObersteiner Jul 23 '21 at 06:02
  • hi row 5 provides eg of data I'm trying to convert to list. I've created a work around, posting an answer below, but if you have a better way using vectorized pandas method, I'd appreciate it. – SModi Jul 23 '21 at 16:03

1 Answers1

0

This is the work around I finally came up with. But would welcome a better method that doesn't require splitting each date.

valdts = dfmap.loc[row, 'valdata'].split(', ')
print(valdts)
>>
['1/1/1990', '6/6/1990', '7/4/1776']

for dt in valdts:
    ldt = dt.split('/')
    valdt = datetime(int(ldt[2]), int(ldt[1]), int(ldt[0]))
    ldates.append(valdt)
print(ldt)
>>

note1: datetime.datetime didn't work for me because of the way I'd imported datetime. See excellent explanations here.

note2: converting the individual numbers to int was crucial. nothing else worked for me. Credit to the solution provided by @waitingkuo in the same link above.

SModi
  • 125
  • 14