Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How To Rename A Text File With DateTime

I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.

Any help would be greatly appreciated.

like image 983
The Woo Avatar asked Mar 07 '11 10:03

The Woo


3 Answers

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

Have a look over here for time stuff and over here for renaming files.

like image 165
phimuemue Avatar answered Oct 15 '22 11:10

phimuemue


To get the current datetime use:

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

Then to rename file:

import os
newname = 'file_'+dt+'.txt'
os.rename('text.txt', newname)
like image 45
ikostia Avatar answered Oct 15 '22 13:10

ikostia


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)

Modify dst and strftime the date as required.

like image 28
DisplacedAussie Avatar answered Oct 15 '22 12:10

DisplacedAussie