-2

I have a list of DateTime object in a generator

l = [datetime.date(2016, 1, 7), datetime.date(2016, 1, 14), datetime.date(2016, 1, 21), datetime.date(2016, 1, 28), datetime.date(2016, 2, 4)]

How can we convert that into a list of date strings format?

output :

['2016-01-07', '2016-01-21', '2016-01-28', '2016-03-04']
sam
  • 18,509
  • 24
  • 83
  • 116
  • The `datetime` documentation shows you how to format a `datetime` value to a string of your choosing. `apply` that to the list. Where are you stuck with the process? – Prune Jun 08 '21 at 17:21
  • 1
    `s = [str(x) for x in l]` it is fairly trivial. – Yoshikage Kira Jun 08 '21 at 17:21
  • Why I run your command, I get your expected output. –  Jun 08 '21 at 17:21
  • Does this answer your question? [Convert a list of DateTime objects to string in python](https://stackoverflow.com/questions/54527912/convert-a-list-of-datetime-objects-to-string-in-python) – Yoshikage Kira Jun 08 '21 at 17:25
  • no but found the answer now. thank you for your inputs. – sam Jun 08 '21 at 17:26
  • You have been on stack overflow for a while. You should know all the rules by now. And yes, this does answer your question. – Yoshikage Kira Jun 08 '21 at 17:26
  • The question is not repeated, it's different and I have added it because many beginners need such basics. If the question asked, doesn't mean that, one should compare the question with points. It might have been for everyone especially beginners. – sam Jun 08 '21 at 17:27

2 Answers2

2

using datetime.strftime

import datetime
l = [datetime.date(2016, 1, 7), datetime.date(2016, 1, 14), datetime.date(2016, 1, 21), datetime.date(2016, 1, 28), datetime.date(2016, 2, 4)]
date_string = [d.strftime('%m-%d-%y') for d in l]
print(date_string)
Jab
  • 26,853
  • 21
  • 75
  • 114
Rima
  • 1,447
  • 1
  • 6
  • 12
1

You can use map and get the required output as follows:

import datetime
l = [datetime.date(2016, 1, 7), datetime.date(2016, 1, 14), datetime.date(2016, 1, 21), datetime.date(2016, 1, 28), datetime.date(2016, 2, 4)]
output = list(map(lambda x:x.strftime('%Y-%m-%d'),l))
print(output)
# ['2016-01-07', '2016-01-21', '2016-01-28', '2016-03-04']