[英]TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
I am trying to get date from pickle file and add one day to the date. 我想从泡菜文件中获取日期,并将日期添加一天。 The print statement returns 2018-09-10 . 打印语句返回2018-09-10 。 Then getting error 'strftime' requires a 'datetime.date' object but received a 'str'
on datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d')
line 然后,获取错误'strftime' requires a 'datetime.date' object but received a 'str'
在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 2018年9月10日
File "C:/Users/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py", line 81, in init fetchData() File "C:/Users/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py", line 15, in fetchData news.init() File "C:\\Users\\Arvinth Kumar\\Downloads\\strtsmrt-master\\news.py", line 58, in init getNews() File "C:\\Users\\Arvinth Kumar\\Downloads\\strtsmrt-master\\news.py", line 38, in getNews dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str' 文件“ C:/ Users / Arvinth Kumar / Downloads / strtsmrt-master / gendata.py”,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'
Please help! 请帮忙!
There is a demo for you to show the difference between strptime and strftime . 有一个演示向您展示strptime和strftime之间的区别。
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()
dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d')
This piece of your code above creates a string from datetime, so anyway you would have to add time first, then convert to string. 上面的这段代码从datetime创建了一个字符串,因此无论如何您都必须先添加时间,然后再转换为string。
For reverse you should use strptime()
instead of strftime()
, this way you'll get datetime from string. 对于反向,应该使用strptime()
而不是strftime()
,这样您将从字符串中获取日期时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.