可以用標準庫中的 datetime:
from datetime import datetime, timedelta
with open('data', 'r') as f:
datetimes = [datetime.strptime(line.strip(), "%Y-%m-%d %H:%M:%S") for line in f]
def get_dhms(td):
"""
given a timedelta then return corresponding days/hours/minutes/seconds
"""
seconds = td.total_seconds()
# return seconds/86400, seconds/3600, seconds/60, seconds # 如果不捨去小數點,用此行
return seconds//86400, seconds//3600, seconds//60, seconds
for dt in datetimes[1:]:
td = (dt - datetimes[0])
print dt, 'vs', datetimes[0], '->', get_dhms(td)
測試資料 data:
2001-10-09 15:41:54
2001-10-19 15:41:55
2001-10-29 15:42:54
2001-10-31 06:00:55
2002-01-01 23:59:59
2011-01-01 23:59:59
結果:
2001-10-19 15:41:55 vs 2001-10-09 15:41:54 -> (10.0, 240.0, 14400.0, 864001.0)
2001-10-29 15:42:54 vs 2001-10-09 15:41:54 -> (20.0, 480.0, 28801.0, 1728060.0)
2001-10-31 06:00:55 vs 2001-10-09 15:41:54 -> (21.0, 518.0, 31099.0, 1865941.0)
2002-01-01 23:59:59 vs 2001-10-09 15:41:54 -> (84.0, 2024.0, 121458.0, 7287485.0)
2011-01-01 23:59:59 vs 2001-10-09 15:41:54 -> (3371.0, 80912.0, 4854738.0, 291284285.0)
函數 get_dhms 會吃進一個 timedelta(時間差) 參數,並且回傳一個 4 元素 tuple 分別是這個 時間差 轉換出來的:
(日數,小時數,分鐘數, 秒數)