我正在尝试实现以下内容:一个返回第三个最新日期的函数,给定这样一个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()
答案 0 :(得分:1)
strftime 根据格式将日期时间对象转换为字符串。
替换:
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。