Skip to content
Advertisement

How to import strftime() and strptime() in Python IDLE

I tried to make a result that can show “Night club” on Staurday, “Blue Monday” on Monday, and “No way” on the other days.

The below is my code.

from datetime import strftime

today = datetime.strptime("date_string, %A")

if today == 'Saturday':
    print('Night club')

elif today == 'Monday':
    print('Blue Monday')
else:
    print('No way')

The system said that “cannot import name ‘strftime’ from ‘datetime'”, how to revise the code?

Advertisement

Answer

As comment said, strftime() and strptime() are methods of classes, rather than functions which you can import directly. So what you need to import is the relevant class.

In your case, strptime() is likely not the thing you need, you are not going turn a date_string (which is not given in your code) to a datetime object, but instead opposite, turning a datetime object to a weekday string.

strftime() can be use but it’s not neccessary, you can use isoweekday() or weekday() method in date and datetime classes, they return the day of the week as an integer, one from 1-7 and another from 0-6.

As you don’t need time information, I will choose the date class here:

# import the date class
from datetime import date

# use today() to get today date and use isoweekday() to get week day integer(1-7)
today = date.today().isoweekday()

if today == 6:
    print('Night club')
elif today == 1:
    print('Blue Monday')
else:
    print('No way')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement