问题
I have a list of strings.
date_str = ["2012-11-04 1:05:21", "2013-11-03 1:05:21", "2014-11-02 1:07:31"]
I want to read them as datetime objects. For one string, I do
datetime.strptime(date_str[1], "%Y-%m-%d %H:%M:%S")
but I don't know how to create a list of datetime objects. If I use
datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
I get this error:
TypeError: must be string, not list
I tried using a loop:
x = datetime.strptime(date_str[0], "%Y-%m-%d %H:%M:%S")
for i in range(1,len(date_str)):
x.append(datetime.strptime(date_str[i], "%Y-%m-%d %H:%M:%S"))
but I get the following error
AttributeError: 'datetime.datetime' object has no attribute 'append'
Is there a way to create a list of datetime objects?
回答1:
x
must be a list:
x = []
for i in range(len(date_str)):
x.append(datetime.strptime(date_str[i], "%Y-%m-%d %H:%M:%S"))
then, you can append all your datetime objects. Or even more Pythonian:
x = [datetime.strptime(s, "%Y-%m-%d %H:%M:%S") for s in date_str]
来源:https://stackoverflow.com/questions/35878175/create-a-list-of-datetime-objects-using-datetime-strptime