如何在文件名前面添加时间戳

1.使用windows批处理脚本实现。

新建记事本,打开后输入:

set "name=%date:~0,10%" #获取系统时间并赋值给name

ren "%~1" "%name:/=%-%~n1%~x1" #将文件重命名为时间+原文件名

保存为windows批处理脚本(.bat)。

然后将你想添加时间戳的文件拖到脚本上就可以了。

2.后来作为练习,又使用python实现了一下这个功能。

代码如下:

#!/usr/bin/python

# coding = utf-8

import datetime

import tkinter as tk

from tkinter import filedialog

import os

curr_time = datetime.datetime.now() #获取当前系统时间

year = str(curr_time.year)

if (curr_time.month < 10):

month = "0" + str(curr_time.month)

else:

month = str(curr_time.month)

if (curr_time.day < 10):

day = "0" + str(curr_time.day)

else:

day = str(curr_time.day)

time_str = year + month + day

root = tk.Tk() #打开文件选择窗口

root.withdraw()

Fpath = filedialog.askopenfilename()

ls = Fpath.split('/') #获取文件名

filename = ls[len(ls) - 1]

del(ls[-1])

filename2 = time_str + '-' + filename

ls.append(filename2) #形成新路径

new_path = '/'.join(ls)

os.rename(Fpath, new_path)

可以打开文件选择窗口选择想要添加时间戳的文件,选中后即可自动添加。