想要为两个文件添加时间戳

时间:2011-08-16 10:57:07

标签: python mysql django timestamp gzip

我的views.py文件中有两行。

views.py

os.popen3("mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup.sql")
os.popen3("gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup.gz"

我希望能够在每个文件backup.sqlbackup.gz中执行此操作。我希望它们能够加上时间戳。所以这意味着我想在这些文件的名称中看到日期。例如,文件名backup-16-Aug-2011.gz

1 个答案:

答案 0 :(得分:2)

from subprocess import Popen, PIPE
from datetime import datetime

# yes, this is me being lazy and not wanting to write a format string.
date = datetime.today().isoformat().split('T')[0]

mysql = "mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup-{}.sql".format(date)
gzip = "gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup-{}.gz".format(date)

Popen(mysql, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell = True)
Popen(gzip, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell = True)

或者,对于旧版本的Python,

from datetime import datetime
import os

date = datetime.today().isoformat().split('T')[0]

mysql = "mysqldump -u *username* -p*password* *database* > /usr/local/src/djcode/c2duo_mms/backup-%s.sql" % date
gzip = "gzip -c /usr/local/src/djcode/c2duo_mms/backup.sql > /usr/local/src/djcode/c2duo_mms/backup-%s.gz" % date

os.popen3(mysql)
os.popen3(gzip)