1

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'

1
  • Your code works in my machine using Python 2.7 and I delete the last line 'end' Commented Jul 22, 2014 at 6:28

1 Answer 1

1

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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.