【问题标题】:TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'TypeError:描述符“strftime”需要一个“datetime.date”对象但收到一个“str”
【发布时间】:2018-09-11 15:04:01
【问题描述】:

我正在尝试从 pickle 文件中获取日期并将日期添加一天。打印语句返回 2018-09-10 。然后在datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') 行上出现错误'strftime' requires a 'datetime.date' object but received a 'str'

Import pickle

dataHistFile = open('dat.pkl', 'rb')
dataHist = pickle.load(dataHistFile, encoding='bytes')
print(dataHist['last_updated'])
dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d')
date = dt_obj + datetime.timedelta(days=1)

2018-09-10
文件“C:/用户/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py”,第 81 行,在 init 中 fetchData() 文件“C:/Users/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py”,第 15 行,在 fetchData news.init() 文件“C:\Users\Arvinth Kumar\Downloads\strtsmrt-master\news.py”,第 58 行,在 init getNews() 文件“C:\Users\Arvinth Kumar\Downloads\strtsmrt-master\news.py”,第 38 行,在 getNews dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') TypeError: 描述符 'strftime' 需要一个 'datetime.date' 对象但收到了 'str'

请帮忙!

【问题讨论】:

  • 你对type(dataHist) 有什么看法?和type(dataHist['last_updated'])?
  • 我想你想要strptime()

标签: python datetime


【解决方案1】:

有一个演示给你展示strptimestrftime之间的区别。

import datetime


def datetime_datetime_strptime():
    _datetime = datetime.datetime.strptime(
        "2018-09-09 18:47:30",
        "%Y-%m-%d %H:%M:%S"
    )
    print(str(_datetime))


def datetime_datetime_strftime():
    now = datetime.datetime.now()
    print(now.strftime("%Y/%m/%d"))   # 2018/09/09
    print(now.__format__("%Y/%m/%d")) # 2018/09/09


if __name__ == '__main__':
    datetime_datetime_strftime()
    datetime_datetime_strptime()

【讨论】:

    【解决方案2】:
    dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d')
    

    上面的这段代码从日期时间创建一个字符串,所以无论如何你必须先添加时间,然后转换为字符串。

    对于反向你应该使用strptime()而不是strftime(),这样你就可以从字符串中获取日期时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多