0

I want to convert a list of datetime objects into strings, but am confused on how to accomplish this task.

hm=dt.date(2013,1,2)
t=hm.strftime('%m/%d/%Y')
t

This produces : '01/02/2013'

However, when I change up the variable to be a list of dates as so, it throws off an error.

hm=[dt.date(2013,1,1), dt.date(2013,1,2)]
t=hm.strftime('%m/%d/%Y')
t

Error: list indices must be integers or slices, not datetime.date

Do I need to use some sort of for loop to accomplish this task?

1
  • use a list comprehension: t_strings = [t.strftime('%m/%d/%Y') for t in [dt.date(2013,1,1), dt.date(2013,1,2)]] Commented May 15, 2020 at 12:55

2 Answers 2

2

You need to iterate over the list to convert each individual date into a string:

>>> t = [d.strftime('%m/%d/%Y') for d in hm]

Or if you want a string with all dates converted to a string concatenated by some other string (let's say ,) you can also do as:

>>> s = ', '.join(t)
Sign up to request clarification or add additional context in comments.

2 Comments

How does this look using the standard for looping procedure?
This is what is call list comprehension. You can take a look here
1

If you want to solve this problem with a "conventional" for loop you can use:

import datetime as dt

hm = [dt.date(2013, 1, 1), dt.date(2013, 1, 2)]
t = []

for date in hm:
    t.append(date.strftime('%m/%d/%Y'))

Otherwise the answer posted by dcg would be a cleaner and much better method.

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.