195:日時とエポック秒を相互に変換する
datetimeモジュール と timeモジュール を使います。
現在のエポック秒をとって、日付に変換してみます。 :
>>> import datetime >>> import time >>> day_by_second=time.time() >>> day_by_second 1193533695.3080001 >>> datetime.date.fromtimestamp(day_by_second) datetime.date(2007, 10, 28)
エポック秒をISOフォーマットの日付文字列にします。また任意の書式に変換してみます。 :
>>> datetime.date.fromtimestamp(day_by_second).isoformat()
'2007-10-28'
>>> datetime.date.fromtimestamp(day_by_second).strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B")
'10-28-07 or 28Oct 2007 is a Sunday on the 28 day of October'
UTC(世界標準時)やローカル時間のタプルに変換 :
>>> time.gmtime(day_by_second) #UTC 世界標準時のタプルに変換 (2007, 10, 28, 1, 8, 15, 6, 301, 0) >>> time.localtime(day_by_second) #ローカル時間のタプルに変換 (2007, 10, 28, 10, 8, 15, 6, 301, 0) >>> time.ctime(day_by_second) 'Sun Oct 28 10:08:15 2007'
日付からエポック秒を作るには、時間も含んだタプルを準備する必要があります。
>>> date_tap=datetime.date(2008,4,13) >>> date_tap datetime.date(2008, 4, 13) >>> >>> date_tap=datetime.date(2008,4,13).timetuple() #timetuppleメソッドで時間を含んだタプルを作ります。 >>> date_tap (2008, 4, 13, 0, 0, 0, 6, 104, -1) >>> time.mktime(date_tap) 1208012400.0
関数を作ってみました。ファイルのリストを取って、修正日が指定された日付よりも新しいものを表示します。 :
import datetime
import time
import string
import os
def get_epoctime_from_date(date):
year=int(date.split('-')[0])
month=int(date.split('-')[1])
day=int(date.split('-')[2])
date_tap=datetime.date(year,month,day).timetuple ()
epoc_time=time.mktime(date_tap)
return epoc_time
start_date='2007-10-29'
start_time=get_epoctime_from_date(start_date)
print start_date, 'is', start_time ,'sec from 1970-01-01'
src_dir=os.getcwd()
file_list=os.listdir(src_dir)
print file_list
for file in file_list:
if os.path.getmtime(os.path.join(src_dir,file))> start_time:
print file,' is newer than' ,start_date
>>>
2007-10-29 is 1193583600.0 sec from 1970-01-01
['find_newer_file.py', 'get_file_property.py', 'get_file_property2.py', 'temp']
find_newer_file.py is newer than 2007-10-29
get_file_property.py is newer than 2007-10-29