0
votes

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.

1
Umm, you need to check the strptime docs. You are converting a date to a string representation and then trying to get back the date from the <b>string</b>. Strings don't have a datetime attribute. docs.python.org/3/library/… - Adeel Siddiqui
You can do datetime.strptime(date_str, format) - Adeel Siddiqui

1 Answers

3
votes

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.