AttributeError: module 'datetime' has no attribute 'strptime' in Python

Dung Do Tien May 28 2022 428

 Hi guys, I am a newbie in Python and today I learn about datetime, I want to format datetime to yyyy-mm-dd HH:MM by using strptime() function of datetime module, It is very simple like this:

import datetime
from datetime import date

today = date.today().strftime("%d/%m/%y %H:%M")
dt = datetime.strptime(today, "%d/%m/%y %H:%M")

print(dt)

I ran code above and got an exception AttributeError: module 'datetime' has no attribute 'strptime'. Detail here:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    dt = datetime.strptime(today, "%d/%m/%y %H:%M")
AttributeError: module 'datetime' has no attribute 'strptime'

I'm using Python version 3.9.8 and windows 11.

Thank for any solutions.

Have 1 answer(s) found.
  • B

    Berennice Muzzquiz May 28 2022

    To solve the error, call the strptime() method on the datetime class instead. like this:

    import datetime
    from datetime import date
    
    today = date.today().strftime("%d/%m/%y %H:%M")
    dt = datetime.datetime.strptime(today, "%d/%m/%y %H:%M")
    
    print(dt)

    #Output

    2022-05-28 00:00:00

    Another solution: change the way to import datetime module, please change:

    #from
    import datetime
    #to
    from datetime import datetime

    Like this: 

    from datetime import datetime
    from datetime import date
    
    today = date.today().strftime("%d/%m/%y %H:%M")
    dt = datetime.strptime(today, "%d/%m/%y %H:%M")
    
    print(dt)

    #Output

    2022-05-28 00:00:00

    I hope this answer will useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close