我正在尝试实现以下内容:给定这样一个 Date 对象数组,返回第三个最新日期的函数
这是我想出的解决方案,但出现以下错误:
TypeError: must be string, not date
<小时/>
import datetime
def third_latest():
timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in timestamps]
dates.sort()
sorteddates = [datetime.datetime.strftime(ts, "%Y-%m-%d") for ts in dates]
return str(sorteddates[3])
def main():
third_latest()
if __name__ == "__main__":
main()
最佳答案
strftime根据格式将datetime对象转换为字符串。
替换:
sorteddates = [datetime.datetime.strftime(ts, "%Y-%m-%d") for ts in dates]
与
sorteddates = [ts.strftime("%Y-%m-%d") for ts in dates]
查看 documentation对于strftime。
此外,您还可以查看 working version of your code here .
关于python - 类型错误 : must be string, 不是 strptime 的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016815/