Python - 将数组中的字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30487870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - converting strings in an array to dates
提问by kaksat
I have read an array of strings from a TXT file and saved it as an array (of over thousand values) using such a line:
我已经从 TXT 文件中读取了一个字符串数组,并使用这样一行将其保存为一个数组(超过一千个值):
dates = np.genfromtxt('filename.txt', delimiter=";", usecols=(0), dtype=None)
Next, I would like to convert strings into dates. I tried to use the line:
接下来,我想将字符串转换为日期。我尝试使用该行:
dates2 = dt.datetime.strptime([dates], '"%Y-%m-%d"').date()
however, I got an error:
但是,我收到了一个错误:
TypeError: must be string, not list
类型错误:必须是字符串,而不是列表
I figured out that such a code works fine:
我发现这样的代码工作正常:
data1='"2010-02-28"'
data1_1 = dt.datetime.strptime(data1, '"%Y-%m-%d"').date()
How should I deal with the described problem?
我应该如何处理所描述的问题?
采纳答案by DeepSpace
Note to future readers:Please do not edit this answer. '"%Y-%m-%d"'
is not a mistake. OP's dates are surrounded by quotes.
给未来读者的注意事项:请不要编辑此答案。'"%Y-%m-%d"'
不是错误。OP 的日期用引号括起来。
dates
is a list of strings. So if you want to create a list of dates from its elements:
dates
是一个字符串列表。因此,如果您想从其元素创建日期列表:
dates_list = [dt.datetime.strptime(date, '"%Y-%m-%d"').date() for date in dates]
This line iterates over the strings in the dates
list and using list comprehension to create a new list of dates.
此行迭代dates
列表中的字符串并使用列表理解来创建新的日期列表。
回答by NaabNuts
you can use split for faster result:
您可以使用 split 以获得更快的结果:
from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d").split('-')
Hope I helped!
希望我有所帮助!