python - 类型错误 : must be string, 不是 strptime 的日期

标签 python datetime

我正在尝试实现以下内容:给定这样一个 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/

相关文章:

python - DataSift python API : Difference between datasift. client.subscribe 和 datasift.push.create_from_hash?

python - 什么是计算数字列表百分比变化的最pythonic方法

c# - 为什么 DateTime 到 Unix 时间使用 double 而不是整数?

c# - 在 C# 中将 12 小时格式转换为 24 小时格式

sql - SQL 中的转换日期错误

python - beautifulsoup 以 None 形式返回包含 <br> 标签的数据

python - 多个指标的相关性

python 2.7 : Matching a subtitle events in VTT subtitles using a regular expression

date - 使用 ISO 8601 表示法创建自定义 SAS 日期时间格式

datetime - 如何同步机器时间