Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Date and time as filename
#1
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!!!
Reply
#2
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")
Reply
#3
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")
Reply
#4
Thank you so much Yoriz and snippsat - now my program works as it should!!!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 113 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 312 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Python date format changes to date & time 1418 4 513 Jan-20-2024, 04:45 AM
Last Post: 1418
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 956 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,160 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Wait til a date and time KatManDEW 2 1,390 Mar-11-2022, 08:05 PM
Last Post: KatManDEW
  Date format and past date check function Turtle 5 4,066 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 2,190 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Naming the file as time and date. BettyTurnips 3 2,887 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
  Update Date based on Time/String stevezemlicka 1 1,984 Jan-08-2021, 06:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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