Don P
Don P

Reputation: 63547

Turn an array of date strings into dates

I have an array of date strings ['1/1/2014', '1/2/2014', '1/3/2014', ...], how do I turn that into an array of Date objects?

This will cast 1 cell:

time.strptime(dates[1], '%m/%d/%Y')

But I haven't seen a way to pass in an entire array. I can loop over my array:

date_objects = []
for date in dates:
    date_objects.append(time.strptime(date, '%m/%d/%Y'))
end

Gives an error that ValueError: time data 'Date' does not match format '%m/%d/%Y'

Upvotes: 1

Views: 1283

Answers (1)

alecxe
alecxe

Reputation: 473763

You can use datetime.strptime() and call date() to get datetime.date objects:

>>> from datetime import datetime
>>> l = ['1/1/2014', '1/2/2014', '1/3/2014']
>>> [datetime.strptime(item, '%m/%d/%Y').date() for item in l]
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3)]

Upvotes: 1

Related Questions