Search code examples
pythonpython-3.xstrftime

AttributeError: 'str' object has no attribute 'datetime': Python


This is my code:

# Fetch today's date
Date = datetime.today().strftime('%Y-%m-%d-%H.%M.%S')
# Variable for log file 
LogFile = os.getcwd()
print(LogFile)
os.mkdir("Logs12")
f = open("Password_Expiry_Date_Log_"+(Date)+".txt", "w+")

#Date Calculations
Date_Before = Date.datetime(Days_Before)
Days_After = Date.datetime(Days_After)

When I try to initialize the variable 'Date_Before', i get the error AttributeError: 'str' object has no attribute 'datetime'. However, I need date to be in a string format to write in into a text filename. Is there any workaround for this?

Thanks in advance.


Solution

  • You could do this:

    from datetime import datetime, timedelta
    
    # Fetch today's date
    date = datetime.today()
    
    string_date = date.strftime('%Y-%m-%d-%H.%M.%S')
    
    # Variable for log file 
    log_file = os.getcwd()
    print(log_file)
    os.mkdir("Logs12")
    f = open(f"Password_Expiry_Date_Log_{string_date}.txt", "w+")
    
    f.close()
    
    #Date Calculations
    date_before = datetime.today() - timedelta(days=1)
    days_after = datetime.today() + timedelta(days=1)
    

    I also updated your string names to conform to PEP8

    Edit: I also improved your syntax, please remember that you always need to close your files.