Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Date and time as filename
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 ="%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 ="%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'{}'
file = open(f"/media/pi/Raspberry-Stick/{filename}.txt", "w")
Thank you so much Yoriz and snippsat - now my program works as it should!!!!

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 653 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Naming the file as time and date. BettyTurnips 3 750 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
  Update Date based on Time/String stevezemlicka 1 580 Jan-08-2021, 06:54 PM
Last Post: Gribouillis
  Confusion about [date]time [formatting] Mark17 0 582 Dec-17-2020, 07:25 PM
Last Post: Mark17
  How to print n days back date at give time Mekala 1 655 Oct-10-2020, 03:35 AM
Last Post: bowlofred
  How to add date and years(integer) to get a date NG0824 4 1,005 Sep-03-2020, 02:25 PM
Last Post: NG0824
  Parsing Date/Time from Metar Reports with 6 hourly weather information Lawrence 0 780 May-03-2020, 08:15 PM
Last Post: Lawrence
  Print date, Time and output to file tpolim008 3 927 Mar-26-2020, 06:49 PM
Last Post: ndc85430
  Parsing date time KipCarter 7 2,777 Mar-06-2020, 06:06 PM
Last Post: KipCarter
  date time question pythonlearner1 2 992 Jan-31-2020, 08:01 PM
Last Post: pythonlearner1

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020