AttributeError: ‘str’ 对象没有属性 ‘strftime’

AttributeError: ‘str’ 对象没有属性 ‘strftime’

AttributeError: ‘str’ object has no attribute ‘strftime’

Python“AttributeError: ‘str’ object has no attribute ‘strftime’”发生在我们尝试对strftime()字符串而不是日期时间对象调用方法时。

要解决此错误,请在对象上调用该方法datetime或在调用之前将字符串转换为一个strftime

attributeerror str 对象没有属性 strftime

下面是错误如何发生的示例。

主程序
d = '2024-11-24 09:30:00.000123' # ⛔️ AttributeError: 'str' object has no attribute 'strftime' print(d.strftime('%m,/%d/%Y'))

问题是我们date.strftime()在字符串而不是
datetime对象上调用。

改为在对象strftime()调用方法datetime

datetime要解决该错误,请在调用之前创建一个对象或将您的字符串转换为一个strftime()

主程序
from datetime import datetime # today = datetime.today() # 👈️ for today's date # 👇️ create datetime object d = datetime(2024, 11, 24, 9, 30, 0) # 👇️ call strftime() method on datetime object print(d.strftime('%m/%d/%Y')) # 👉️ 11/24/2024

datetime在调用之前将字符串转换为对象strftime()

如果您有一个字符串并需要将其转换为datetime对象,请使用
datetime.strptime
方法。

主程序
from datetime import datetime d = '2024-11-24 09:30:00.000123' # 👇️ convert string to datetime object datetime_obj = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') # 👇️ Sunday, 24. November 2024 09:30AM print(datetime_obj.strftime("%A, %d. %B %Y %I:%M%p"))

您可以在官方文档的这张表中查看所有支持的格式代码strftime()strptime()方法

将今天的日期打印为 YYYY-MM-DD,将时间打印为 hh:mm:ss

这是一个示例,将今天的日期打印为YYYY-MM-DD,将当前时间打印为hh:mm:ss

主程序
from datetime import datetime today = datetime.today() print(today) # 👉️ "2023-01-29 10:14:14.189836" todays_date = today.strftime('%Y-%m-%d') print(todays_date) # 👉️ "2023-01-29" current_time = today.strftime('%H:%M:%S') print(current_time) # 👉️ "10:14:14"

如果您需要自定义日期或时间的格式,请参阅
此表
以了解支持的格式代码。

The
strftime()
method is supported by date, datetime and time objects and returns a
string that represents the date and time, controlled by an explicit format
string.

Conversely, the
datetime.strptime()
method returns a datetime object that corresponds to the provided date string,
parsed according to the format.

ValueError is raised if the date string and format can’t be parsed by
time.strptime().

The strftime() and strptime() methods support the same
format codes.

A good way to start debugging is to print(dir(your_object)) and see what
attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
my_string = 'bobbyhadz.com' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

If you pass a class to the dir()
function, it returns a list of names of the class’s attributes, and recursively
of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the “AttributeError: str object has no attribute error”.

Since strftime() is not a method implemented by strings, the error is caused.

If the error persists, follow the instructions in my
AttributeError: ‘str’ object has no attribute ‘X in Python
article.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: