I want to put the date in the name of the Python text file

Asked 2 years ago, Updated 2 years ago, 15 views

Python wants to put the current date and time in the name of the text file, but I don't know how to put the variable.

I know how to rename, but instead of specifying a name with a string, I want the file name to reflect the current time when the program was run.The code for the current rewrite is written below.Thank you for your cooperation.

importos
from datetime import datetime

d = datetime.datetime.now()
os.rename("sample.txt", d.txt)

I'd like to put the date and time in part d.

python

2022-09-29 22:14

1 Answers

If you search by python date format, you will find a way to change the datetime type to a string type.
To put the date and time in the d part, rewrite os.rename("sample.txt", d.txt) as follows:

python 2.6 and later

os.rename("sample.txt", "{0:%Y%m%d_%H%M%S}.txt".format(d))

Available before python 2.6

 os.rename("sample.txt", d.strftime("%Y%m%d%H%M%S")+".txt")

Below is a sample code for a series of file creation and renaming.
I tried to keep the extension when renaming.For your information.

#-*-coding:utf-8-*-

import datetime
import shutil
importos

now=datetime.datetime.now()
# Generate a file name that incorporates the current time
fmt_name = "hoge_{0:%Y%m%d-%H%M%S}.txt".format(now)
with open(fmt_name, "w") as f:
    f.write("What time are you?"")
# Create an undated file for testing
plain_name="fuga.piyo.txt" 
shutil.copy(fmt_name,plain_name)
# Add current time immediately before extension
ss=plain_name.split(".", 1)
new_name="{0}_{1:%Y%m%d-%H%M%S}.{2}".format(ss[0], now,ss[1])
# Rename an existing file
os.rename(plain_name, new_name) 


2022-09-29 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.