Python Forum

Full Version: Date and time as filename
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hallo everybody,
I want to have files in the format "2020-08-07_19-57-55.txt" - it´s for measuring purpopses and for having a unique filename. I found:


import datetime

filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

file = open("/media/pi/Raspberry-Stick/filename.txt","w")

The above line gives me an errrormessage - how do I pass the variable "filename" to the "file = open()" command. I tried but didn´t find the answer - I´m new to python. Could use a little help!!!
Using an f string
import datetime
 
filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
 
file = open(f"/media/pi/Raspberry-Stick/{filename}.txt","w")
Can also show that f-string work with datetime.
from datetime import datetime

filename = f'{datetime.now():%Y-%m-%d_%H-%M-%S}'
file = open(f"/media/pi/Raspberry-Stick/{filename}.txt", "w")
Thank you so much Yoriz and snippsat - now my program works as it should!!!!