Module datetime has no attribute strftime как исправить

working with datetime gets very confusing once you consider that datetime is both the package name and a module name inside datetime.

the datetime package has a lot of different modules, namely:

datetime module handles datetime objects.

date module handles date objects.

time module handles time objects.

timedelta module handles timedelta objects.

In your case, when you said import datetime, what you’re really referring to is the datetime package NOT the datetime module.

strftime is a method of datetime objects (i.e. under the datetime module)

therefore, you have 2 ways to go about this.

If you went with import datetime, then you have to specify the package, the module THEN the method, like so:

import datetime

today = datetime.datetime.now()
today.strftime('%Y-%m-%d')

or the better, more human readable way is to just import the datetime module under the datetime package by doing a from *package* import *module*. Applied to the datetime package, that means: from datetime import datetime like so:

from datetime import datetime

today = datetime.now()
today.strftime('%Y-%m-%d')

OR, my preferred method, is to give the module an alias (or basically a «nickname»), so it doesn’t get confusing (LOL):

from datetime import datetime as dt
from datetime import timedelta as td

today = dt.now() # get date and time today
delta = td(days=3) #initialize delta
date_you_actually_want = today + delta # add the delta days
date_you_actually_want.strftime('%Y-%m-%d') # format it

hope that clears it up for you.

This error occurs when you import the datetime module and try to call the strftime() method on the imported module. You can solve this error by importing the datetime class using:

from datetime import datetime

or accessing the class method using

datetime.datetime.strftime()

This tutorial will go through the error and how to solve it with code examples.


Table of contents

  • AttributeError: module ‘datetime’ has no attribute ‘strftime’
  • Example
    • Solution #1: Use the from keyword
    • Solution #2: Use datetime.datetime
  • Summary

AttributeError: module ‘datetime’ has no attribute ‘strftime’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. datetime is a built-in Python module that supplies classes for manipulating dates and times. One of the classes in datetime is called datetime. It can be unclear when both the module and one of the classes share the same name. If you use the import syntax:

import datetime

You are importing the datetime module, not the datetime class. We can verify that we are importing the module using the type() function:

import datetime

print(type(datetime))
<class 'module'>

We can check what names are under datetime using dir() as follows:

import datetime

attributes = dir(datetime)

print('strftime' in attributes)

In the above code, we assign the list of attributes returned by dir() to the variable name attributes. We then check for the strftime() attribute in the list using the in operator. When we run this code, we see it returns False.

False

However, if we import the datetime class using the from keyword and call dir(), we will see strftime as an attribute of the class. We can check for strftime in the list of attributes as follows:

from datetime import datetime

attributes = dir(datetime)

print('strftime' in attributes)
True

Example

Consider the following example, where we want to get create a string representation of a date and time using the strftime() method.

import datetime

now = datetime.datetime.now()

date_string = datetime.strftime(now, "%m/%d/%Y, %H:%M:%S")

print(date_string)

In the above code, we get the current local date and time using the now() method and then pass the datetime object to strftime() with the format. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [1], in <cell line: 5>()
      1 import datetime
      3 now = datetime.datetime.now()
----> 5 date_string = datetime.strftime(now, "%m/%d/%Y, %H:%M:%S")
      7 print(date_string)

AttributeError: module 'datetime' has no attribute 'strftime'

The error occurs because we imported the datetime module and tried to call the strftime() method on the module, but strftime() is an attribute of the datetime class, not the module.

Solution #1: Use the from keyword

We can solve this error by importing the datetime class using the from keyword. Let’s look at the revised code:

from datetime import datetime

now = datetime.now()

date_string = datetime.strftime(now, "%m/%d/%Y, %H:%M:%S")

print(date_string)

Note that we had to change the now() method call from datetime.datetime.now() to datetime.now() as we have imported the datetime class. Let’s run the code to see the result:

05/19/2022, 17:49:40

We successfully created a formatted string representing a date and time.

Solution #2: Use datetime.datetime

We can also solve this error by importing the module and then accessing the class attribute using datetime.datetime, then we can call the strftime() method. Let’s look at the revised code:

import datetime

now = datetime.datetime.now()

date_string = datetime.datetime.strftime(now, "%m/%d/%Y, %H:%M:%S")

print(date_string)

Let’s run the code to get the result:

05/19/2022, 17:49:40

We successfully created a formatted string representing a date and time.

Summary

Congratulations on reading to the end of this tutorial! Remember that from datetime import datetime imports the datetime class and import datetime imports the datetime module.

For further reading on AttributeErrors involving datetime, go to the articles:

  • How to Solve Python AttributeError: ‘datetime.datetime’ has no attribute ‘datetime’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘now’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘strptime’
  • How to Solve Python AttributeError: module ‘datetime’ has no attribute ‘today’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

What causes and solutions to solve the error AttributeError module ‘datetime’ has no attribute ‘strftime’? If you are looking for a solution to this problem, this article is for you. Let’s read it now.

In Python, a datetime module is responsible for working and dealing with issues related to date and time. In the datetime module, there are the following classes: datetime.date, datetime.time, datetime.datetime and datetime.delta. 

The strftime() function returns a string representing the date, time, and time values ​​using the time, date, and datetime classes and they use the format parameters %Y, %m, %d, %H…. in the strftime() function.

The error happens because you call the strftime() function on the datetime module without importing the classes from that module. 

Example: 

import datetime

datetimeStr = datetime.strftime('%m/%d/%Y')
print(datetimeStr)

Output:

Traceback (most recent call last):
 File "./prog.py", line 3, in <module>
AttributeError: module 'datetime' has no attribute 'strftime'

How to solve the AttributeError module ‘datetime’ has no attribute ‘strftime’?

Import datetime class from datetime module

As I mentioned, this error happens when you don’t import datetime class, so just importing datetime class and then using the ‘from’ keyword.

Example:

  • Import datetime class from datetime module.
  • Use datetime.now() to get the current date and time.
  • Then, the strftime() function converts the time format to a string according to the format parameter. The format parameter I leave is month/day/year.
from datetime import datetime

# Use the datetime.now() function to get the current date and time
currentTime = datetime.now()

# Use the strftime() function to convert the time format to a string
datetimeStr = currentTime.strftime('%m/%d/%Y')
print('The datetime object is converted to a string:', datetimeStr)

Output:

The datetime object is converted to a string: 12/10/2022

Or you can use the following shorthand to create a datetime object and call strftime() on that object.

Example:

import datetime

# Use the datetime.now() function to get the current date and time
currentTime = datetime.datetime.now()

# Use the strftime() function to convert the time format to a string
datetimeStr = currentTime.strftime('%m/%d/%Y')
print('The datetime object is converted to a string:', datetimeStr)

Output:

The datetime object is converted to a string: 12/10/2022

Use the assigned name

To avoid overlapping the class name with the module name, you can handle it by assigning it a different name.

Example:

  • Import datetime class from datetime module.
  • Assign a different name than the module name and class name. In this example, I named it ‘lsi’.
  • The now() function is called on the assignment name and returns the current date and time.
  • Call the strftime() function on that datetime object and convert it to a string according to the format parameter.
from datetime import datetime as lsi

# The now() function is called on the assignment name and returns the current date and time
currentTime = lsi.now()

# Use the strftime() function to convert the time format to a string
datetimeStr = currentTime.strftime('%m/%d/%Y')
print('The datetime object is converted to a string:', datetimeStr)

Output:

The datetime object is converted to a string: 12/10/2022

Summary

That is the cause and handling of the AttributeError module ‘datetime’ has no attribute ‘strftime’ I want to convey to you. The key point to solve this error is importing the datetime class from the datetime module. Hope you get it fixed soon.

Maybe you are interested:

  • AttributeError: ‘str’ object has no attribute ‘keys’
  • AttributeError: ‘float’ object has no attribute ‘#’ in Python
  • AttributeError: ‘list’ object has no attribute ‘encode’

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

#python

Вопрос:

Мне нужно запустить скрипт, в котором я должен изменить дату дня в нескольких полях кода, но у меня возникли проблемы с получением скриптом только даты дня, он получает дату только вручную в этом формате:

 import datetime as date  

Data_inicio = dt.date(2020,3, 1) #Ano, mês, Dia #here
Data_Fim =    dt.date(2021,10,29)
 

Я попытался изменить код таким образом:

 import datetime as date  

data = date.datetime.now()
data_today = data.strftime("%Y,%m,%d")
Data_inicio = dt.date(2020,3, 1) 
Data_Fim = dt.date(data_today) 
 

или

 Data_Fim = data_today 
 

Следующая ошибка возникает в data_fim :

 files=glob.glob(url '/*' Data_inicio.strftime("%d%b%Y") '-' Data_Fim.strftime("%d%b%Y") '.txt')
files_inativos =glob.glob(url_inativos '/*'  '.txt')
files = files   files_inativos


AttributeError: 'str' object has no attribute 'strftime'
 

Комментарии:

1. вы должны были сделать, как import datatime as datetime вместо import datatime as date

2. Так ли это на самом деле datatime ? Я думаю, что это должно быть datetime

3. strftime используется для форматирования объектов datetime, поэтому он переводит вас из datetime str в. While strptime используется для разбора строк в объекты datetime, поэтому он ведет вас противоположным путем. В вашем случае вы пытаетесь создать date из строки в Data_Fim , но строка не может быть отформатирована в datetime, ее можно только проанализировать. Для создания из строки используйте strptime

4. Пожалуйста, исправьте свои операторы импорта, чтобы использовать правильные модули

Ответ №1:

Кажется, единственное, что вы хотите, это установить переменную «дата окончания» в качестве вашей data_today , но как datetime объект, а не строку. Проблема в том, что вы пытаетесь сделать это непосредственно из строки, но в строках нет методов для преобразования даты и времени. Чтобы использовать их, вы можете использовать datetime.strptime() , например:

 from datetime import datetime 

date_today = datetime.today().strftime("%Y, %m, %d")
start_date = datetime(2020, 3, 1)
end_date = datetime.strptime(date_today, "%Y, %m, %d")
 

Это создает строку для «сегодня» (с именем date_today ), создает datetime объект для начальной даты (с именем start_date ), затем создает переменную конечной даты ( end_date ), которая фактически анализируется из существующей строки. В частности, в этом случае эта строка — та, которую мы только что создали ( date_today ) .

Обратите внимание, что этот пример имеет в основном обучающие цели, поскольку нет смысла создавать строку «today» из datetime , а затем анализировать ее обратно в datetime объект. Синтаксический анализ имел end_date бы гораздо больше смысла, если бы вы получали его date_today из другого места, но с известным форматом, и в этом случае вы можете преобразовать его в datetime объект и использовать его. Однако на самом деле вам не нужно использовать строковое представление «сегодня» в том же контексте.

Если это тот случай, когда вы определяете их в одном контексте, то, вероятно, вам вообще не нужны 2 переменные, и вы можете использовать только datetime объект. Всякий раз, когда вам нужно распечатать его или отобразить в виде строки, вы можете отформатировать его для этого конкретного вывода. Например:

 from datetime import datetime 

start_date = datetime(2020, 3, 1)
end_date = datetime.today()

print(end_date.strftime("%Y, %m, %d"))
>>> 2021, 10, 29
 

Обратите внимание, что если вы обрабатываете даты и время, обычно лучше просто использовать datetime объекты и форматировать их всякий раз, когда требуется выходная строка. Экономит много работы и туда и обратно форматирование-разбор-форматирование-разбор материала. Кроме того, это позволяет вам использовать временные интервалы.

Ответ №2:

Похоже, что вы создаете datetime объект, а затем пытаетесь извлечь часть этого объекта (только date часть). Вы можете решить эту проблему, создав экземпляр date datetime объекта or и извлекая нужные атрибуты:

 import datetime

# Using date objects
start_date = datetime.date(year=2020, month=3, day=1)
end_date = datetime.date.today()

# Using datetime objects (will include hours, minutes, seconds...)
start_date = datetime.datetime(year=2020, month=3, day=1)
end_date = datetime.datetime.today()

# You can format either object with the `.strftime()` method
date_now = datetime.date.today()
datetime_now = datetime.date.today()

for dt in [date_now, datetime_now]:
    # format and print
    print(dt.strftime('%Y,%m,%d'))
    
    # Or access the attributes directly
    print([dt.year, dt.month, dt.day])
 

Комментарии:

1. спасибо, я ломал голову над решением.

Я пытался узнать сегодняшний год, месяц и день, используя дату и время. Итак, я импортировал модуль datetime, используя import datetime. Однако мне также понадобилась команда timedelta, поэтому я использовал from datetime import timedelta. Я также использую strftime, который, я думаю, получен из from datetime import datetime. Тем не менее, я не могу запустить все это сразу.

Итак, как я могу использовать модуль datetime с strftime и timedelta? Любая помощь приветствуется!

2 ответа

Лучший ответ

Работа с datetime становится очень запутанной, если учесть, что datetime одновременно является именем пакета и именем модуля внутри datetime.

В datetime пакете много разных модулей, а именно:

Модуль datetime обрабатывает объекты datetime.

Модуль date обрабатывает объекты даты.

Модуль time обрабатывает объекты времени.

Модуль timedelta обрабатывает объекты timedelta.

В вашем случае, когда вы сказали import datetime, на самом деле вы имеете в виду datetime package НЕ datetime < em> модуль .

strftime — это метод datetime объектов (т.е. в модуле datetime)

поэтому у вас есть 2 способа сделать это.

Если вы выбрали import datetime, тогда вы должны указать пакет, модуль ЗАТЕМ метод, например:

import datetime

today = datetime.datetime.now()
today.strftime('%Y-%m-%d')

Или лучший, более понятный для человека способ — просто импортировать модуль datetime в пакет datetime, выполнив from *package* import *module*. Применительно к пакету datetime это означает: from datetime import datetime вот так:

from datetime import datetime

today = datetime.now()
today.strftime('%Y-%m-%d')

ИЛИ, мой предпочтительный метод, — дать модулю псевдоним (или, по сути, «псевдоним»), чтобы это не сбивало с толку (LOL):

from datetime import datetime as dt
from datetime import timedelta

today = dt.now() # get date and time today
delta = td(days=3) #initialize delta
date_you_actually_want = today + delta # add the delta days
date_you_actually_want.strftime('%Y-%m-%d') # format it

Надеюсь, что это проясняет вам это.


6

zero
27 Апр 2018 в 02:36

Ваша ошибка module 'datetime' has no attribute 'strftime' говорит о том, что проблема не в импорте, а в том, как вы вызываете метод strftime().

strftime() — это метод в классе datetime (который, как ни странно, является частью модуля datetime), поэтому вам необходим экземпляр объекта datetime для его вызова. Например:

# import datetime class from the datetime module:
from datetime import datetime

# instantiate a new datetime object:
a = datetime(12, 10, 30, 11, 23, 45)

# call the strftime() method on the object:
print(a.strftime("%H:%M:%S %Z"))
# 11:23:45


1

Richard Inglis
27 Апр 2018 в 04:04

Понравилась статья? Поделить с друзьями:
  • Как найти точки максимума минимума на отрезке
  • Как исправить косоглазие у взрослых секретный метод бейтса
  • Как найти фильм про цветок
  • Как найти мальчика для любви
  • Как найти стационарную точку в математике