错误原因:
该错误通常出现Pyhton的日期和时间格式化的过程中,因为strftime
是将日期格式化输出的函数,该函数属于datetime
库中datetime
类的函数。出现该错误的原因是:变量是字符串类型的日期,而字符串类型是没有strftime
函数的。
解决方法:
如果你想要对一个字符串类型的日期时间进行格式化处理,首先需要将它转化为日期时间类型的变量,否者就出'str' object has no attribute 'strftime'
错误出现。将一个字符串类型的日期转换为日期时间对象一般有两种方法,一种是通过datetime
包,另一种是使用dateutil
包。
-
方法一:使用
datetime
模块中的strptime
函数将字符串类型的日期转换为日期时间对象,然后再使用strftime
函数进行时间格式化处理。例如:from datetime import datetime if __name__ == '__main__': str_date = '2023-09-13T05:43:39.523000Z' # 输出str_date的类型 print(type(str_date)) # <class 'str'> date_parse = datetime.strptime(str_date, '%Y-%m-%dT%H:%M:%S.%fZ') # 输出date_parse的类型 print(type(date_parse))# <class 'datetime.datetime'> print(date_parse) # 2023-09-13 05:43:39.523000 date_format = date_parse.strftime('%Y%m%d%H%M%S') # 输出date_format的类型 print(type(date_format)) # <class 'str'> print(date_format)# 20230913054339
-
方式二:使用Python中的
dateutil
包,这个包可以识别大部分常见的日期格式,通过包中parser
类的parse
方法,将字符串类型的日期转换为日期时间对象。例如:from dateutil import parser if __name__ == '__main__': str_date = '2023-09-13T05:43:39.523000Z' # 输出str_date的类型 print(type(str_date)) # <class 'str'> date_parse = parser.parse(str_date) # 输出date_parse的类型 print(type(date_parse)) # <class 'datetime.datetime'> print(date_parse) # 2023-09-13 05:43:39.523000+00:00 date_format = date_parse.strftime('%Y%m%d%H%M%S') # 输出date_format的类型 print(type(date_format)) # <class 'str'> print(date_format) # 20230913054339
- 39 attribute strftime object str39 attribute strftime object 39 attribute nonetype object 39 unsupported typeerror str strip python 39 str 39 quot attributeerror attribute 39 attributeerror attribute nonetype 39 attributeerror tensorflow attribute 39 attributeerror antialias attribute 39 attribute nonetype children 39 attributeerror attribute copy_src