1

I have str list

startDateTimes = ["2011/12/13 00:00","2011/12/13 03:00","2011/12/15 05:00"]
datetime.datetime.strptime(startDateTimes[0],'%Y/%m/%d %H:%M')

Now I want to use strptime for all items in list.

I think I should use map though, still not clear to me.

For example

map(datetime.datetime.strptime,startDateTimes)

Where should I put %Y/%m/%d %H:%M?

whitebear
  • 11,200
  • 24
  • 114
  • 237
  • 1
    I consider closing of the question a bit harsh without additional explanation. As I understand, the approach suggest in the linked question is, to call map with 3 arguments, the `strptime` function, an iterator delivering the data format (e. g. `itertools.repeat`) and the startDateTimes list. – guidot Jan 07 '22 at 10:27
  • Yes, Maybe it is me not getting the rules 100% and I agree that some questions would require minimal effort to find an answer but, at the end of the day, it is a "help" forum and not a book. I myself think this did not deserve to be closed - for what it counts :-) – nikeros Jan 09 '22 at 12:03

3 Answers3

1

Why not a list comprehension?

[datetime.datetime.strptime(x, '%Y/%m/%d %H:%M') for x in startDateTimes]

You could use map like this:

def parse(x): return datetime.datetime.strptime(x, '%Y/%m/%d %H:%M')

list(map(parse, startDateTimes))

OUTPUT

[datetime.datetime(2011, 12, 13, 0, 0), datetime.datetime(2011, 12, 13, 3, 0), datetime.datetime(2011, 12, 15, 5, 0)]

You could clearly have a one-liner and move the definition of the parse function as a lambda within map - just wanted to make it clearer.

nikeros
  • 3,302
  • 2
  • 10
  • 26
1

You can use a lambda here

map(lambda dt: datetime.datetime.strptime(dt,'%Y/%m/%d %H:%M'),startDateTimes)
Simon Hawe
  • 3,968
  • 6
  • 14
1

You can use functools.partial for this, it allows you to create a function which will apply given arguments by default. Example:

from functools import partial

dates = map(partial(datetime.datetime.strptime, format='%Y/%m/%d %H:%M'), startDateTimes)
guidot
  • 5,095
  • 2
  • 25
  • 37
Paradoxis
  • 4,471
  • 7
  • 32
  • 66