Home > other >  python: datetime strftime not working properly with file naming
python: datetime strftime not working properly with file naming

Time:06-13

here is my code:

from datetime import date
from datetime import datetime

time = date.today().strftime("%Y-%m-%d-%H-%M-%S")
f = open(r'C:/folder'   time   '.txt', 'w')
f.write("Something")
f.close()

But output is e.g. 2022-06-13-00-00-00 at 14:19:53. Could you, please, hint me how to fix it?

CodePudding user response:

You are using date.today(), which returns today's date without any time set.
You want to use datetime.now(), which returns the date along with the time.

So, you should change your code to the following.

from datetime import datetime

time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
f = open(r'C:/folder'   time   '.txt', 'w')
f.write("Something")
f.close()

CodePudding user response:

Try using this -

 from datetime import datetime
 time_curr = datetime.now()
 print(time_curr)
  • Related