pythonで日付によるファイルの選別

さくらのVPSでバックアップしたファイルをGoogle Driveに転送して保管するために、pythonで転送対象のファイルを日付で選択するスクリプトを作りました。

やりたいこと

最終目標

当日分のバックアップファイルをGoogle Driveに転送する。

今回の課題

当日分のバックアップファイルのファイル名をpythonスクリプトで取得する。

参考:バックアップ処理

crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
  10  3  *  *  * root /home/root/backup/backup.sh 1>/dev/null

夜中の3時10分にバックアップシェルスクリプトを実行しています。

バックアップシェルスクリプト

■ backup.sh

#!/bin/sh
WWWBACKUP_FILENAME="wwwbackup-`date '+%Y-%m-%d'`.tar.gz"
KEEPDAY=7
OLDDATE=`date --date "$KEEPDAY days ago" '+%Y-%m-%d'`

#backup WordPress, API directory
/bin/find /var/www/reirou > ./backuplist.txt
/bin/find /var/www/gmc/public_html/wordpress >> ./backuplist.txt
/bin/find /var/www/gmc/gmc_api >> ./backuplist.txt

/bin/tar -zpcPT ./backuplist.txt -f "$WWWBACKUP_FILENAME"
/bin/chmod 755 "$WWWBACKUP_FILENAME"

#transfer backed-up files to Google Drive
# TODO: 

#remove old files
rmfile="wwwbackup-$OLDDATE.tar.gz"
if [ -e $rmfile ]; then
        echo "$rmfile is removing"
        /bin/rm -f $rmfile
fi

バックアップファイルは1週間分だけ保存して、それより古いファイルは削除しています。

“# TODO:”の部分に完成したpythonスクリプトの処理を入れる予定です。

バックアップされたファイル

こんな感じで毎日保存されています。

-rwxr-xr-x 1 root root 1172599580  1月 24 03:11 2013 wwwbackup-2013-01-24.tar.gz
-rwxr-xr-x 1 root root 1172592143  1月 25 03:11 2013 wwwbackup-2013-01-25.tar.gz
-rwxr-xr-x 1 root root 1173426517  1月 26 03:11 2013 wwwbackup-2013-01-26.tar.gz
-rwxr-xr-x 1 root root 1177605759  1月 27 03:11 2013 wwwbackup-2013-01-27.tar.gz
-rwxr-xr-x 1 root root 1178057670  1月 28 03:11 2013 wwwbackup-2013-01-28.tar.gz
-rwxr-xr-x 1 root root 1178319271  1月 29 03:11 2013 wwwbackup-2013-01-29.tar.gz
-rwxr-xr-x 1 root root 1178883881  1月 30 03:12 2013 wwwbackup-2013-01-30.tar.gz

 

転送ファイルを選択するpythonスクリプト

■ remoteBackup.py

# coding: UTF-8
import os, time, re

def backup_files(filename_pattern_str, from_days):
	today = time.localtime()
	today_epoch_delta = time.mktime(today)
	from_day_epoch_delta = today_epoch_delta - from_days*24*60*60

	print 'today:', time.ctime(today_epoch_delta)
	print 'from_day:', time.ctime(from_day_epoch_delta)

	src_dir = os.getcwd()
	files = os.listdir(src_dir)
	ret_files = []
	for file in files:
		file_upd_time = os.path.getmtime(file)
		filename = os.path.basename(file)
		if file_upd_time <= from_day_epoch_delta:
			continue
		if re.search(filename_pattern_str, filename):
			ret_files.append(filename)
	return ret_files
#------------------------------------------------------------------------------
# Transfer backup files to Google Drive
#------------------------------------------------------------------------------
files = backup_files("gz$", 1)
for filename in files:
	print "backup file = %s" % filename
	# TODO:

カレントディレクトリにあるファイルのうち、1日以内に作成・更新されたファイルの名前を配列にして返す関数をつくりました。

意図しないファイルが含まれないよう、念のために、ファイル名を正規表現でマッチングしています。(ファイル名が’gz’が終わるファイル)

“# TODO:”の部分に完成したGoogle Driveにファイルを転送する処理を入れる予定です。

 

日付処理

pythonでは、大雑把に次の形式で日付を扱うようです。

  • epoch(基準日時)からの経過秒数
  • 日付の要素を分解した配列 struct_time(年、月、日…)

ファイルの更新日付

ファイルの更新日付を返す関数os.path.getmtime()が返す日付形式は、「epochからの経過秒数」形式とドキュメントにあります。

10.1. os.path — 共通のパス名操作:os.path.getmtime(path)
path の最終更新時刻を、エポック (time モジュールを参照下さい) からの経過時間を示す秒数で返します。ファイルが存在しなかったりアクセスできない場合は os.error を送出します。

 現在日付の取得

time.localtime()という関数で時差を考慮した struct_time形式の現在日時が取得できるようです。

ファイル更新日付と比較するためにmktime()という関数を使って日付の形式を変換しました。

日付形式の相互変換

参考:15.3. time — 時刻データへのアクセスと変換

From

To

Use

epochからの秒数

struct_time in UTC

gmtime()

epochからの秒数

struct_time in local time

localtime()

struct_time in UTC

epochからの秒数

calendar.timegm()

struct_time in local time

epochからの秒数

mktime()

 

次のステップ

次は、今まで作ったGoogle Driveへファイル転送するスクリプトと組み合わせる予定です。Google Driveの容量は少ないので、Google Drive上の古いバックアップファイルの自動削除の仕組みも組み込む予定です。

 


関連記事