create a list of datetime objects using datetime.strptime

你。 提交于 2019-12-11 23:15:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!