The Woo
The Woo

Reputation: 18645

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.

Upvotes: 9

Views: 40035

Answers (4)

gladysbixly
gladysbixly

Reputation: 2659

import os
import datetime

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))

Upvotes: 1

DisplacedAussie
DisplacedAussie

Reputation: 4694

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.

Upvotes: 1

phimuemue
phimuemue

Reputation: 35983

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.

Upvotes: 31

ikostia
ikostia

Reputation: 7587

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)

Upvotes: 12

Related Questions