Python - How to rename a text file using DateTime

I am using Python v2.x and wondering how I can rename a known text file since my example says β€œtext.txt” to include the current date and time.

Any help would be greatly appreciated.

+4
source share
4 answers

To use the current datetime usage:

import datetime dt = str(datetime.datetime.now()) 

Then rename the file:

 import os newname = 'file_'+dt+'.txt' os.rename('text.txt', newname) 
+10
source

os.rename("text.txt", time.strftime("%Y%m%d%H%M%S.txt")) . Note that you must import os and time .

Look here for time and more here for renaming files.

+25
source

os.rename (src, dst)

 import os import datetime src = '/home/thewoo/text.txt' dst = '/home/thewoo/%s-text.txt' % datetime.datetime.now() os.rename(src, dst) 

Change the dst and strftime date as needed.

+1
source
 import os import date timestamp = datetime.datetime.now() t = timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second split_filename = filename.split('.') os.rename(filename, split_filename[:-1] + '_' + '-'.join(t)) 
+1
source

Source: https://habr.com/ru/post/1342616/


All Articles