Last active
August 29, 2015 14:02
-
-
Save mperlet/cd1a6e18e00dc5ea17b0 to your computer and use it in GitHub Desktop.
last.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import commands | |
import datetime | |
import time | |
import sys | |
user = commands.getoutput('echo $USER') | |
last = commands.getoutput('last -F $USER | grep ":0 .* :0" | sed "s/\s\s*/ /g" | grep -v "(00:00)"').split('\n') | |
last = [x.replace('%s :0 :0 ' % user, '') for x in last] | |
last_dict = {} | |
for el in last: | |
month = el.split()[1] | |
year = el.split()[4] | |
el_el = el.replace('%s ' % month, '') | |
el_el = el_el.replace('%s ' % year, '') | |
el_el = el_el.replace('- %s %s ' % (el_el.split()[0], el_el.split()[1]), '') | |
key = '%s-%s' % (year, month) | |
if not last_dict.has_key(key): | |
last_dict[key] = [el_el] | |
else: | |
last_dict[key] = last_dict[key] + [el_el] | |
def get_month_time(month_list): | |
total_h = 0 | |
total_m = 0 | |
for el in month_list: | |
el = fix_row(el) | |
t = el.split()[-1].replace('(','').replace(')','') | |
try: | |
h, m = t.split(':') | |
if h.isalnum() and m.isalnum(): | |
if int(h) > 0: | |
total_h = total_h + int(h) | |
total_m = total_m + int(m) | |
elif m.isalnum(): | |
days, hours = h.split('+') | |
total_m = total_m + int(m) | |
total_h = total_h + int(hours) | |
total_h = total_h + int(days) * 24 | |
except: | |
pass | |
total_h = total_h + total_m / 60 | |
total_m = total_m % 60 | |
return [total_h, total_m] | |
def print_month(month,di): | |
print month | |
for o in di[month]: | |
print fix_row(o) | |
def time_date_diff(FMT, date_a, date_b): | |
tdelta = datetime.datetime.strptime(date_a, FMT) - datetime.datetime.strptime(date_b, FMT) | |
return time.strftime('(%H:%M)', time.gmtime(float(tdelta.seconds))) | |
def fix_row(el): | |
FMT = '%H:%M:%S' | |
day = datetime.datetime.today().strftime(FMT) | |
el = el.split() | |
if len(el[1]) == 1: | |
el[1] = '0%s' % el[1] | |
if el[3] == 'still': | |
el[3] = day | |
el[4] = time_date_diff(FMT, day, el[2]) | |
return '%s' % ' '.join(el[:5]) | |
def run(): | |
if len(sys.argv) == 2 and sys.argv[1].isdigit(): | |
show_count = int(sys.argv[1]) | |
else: | |
show_count = 2 | |
for m in reversed(range(0, show_count)): | |
mm = (datetime.date.today() - datetime.timedelta(m*365/12)).strftime('%Y-%b') | |
hh, minmin = get_month_time(last_dict[mm]) | |
print "************** %s :: Hours: %s Minutes: %s **************" % (mm, hh, minmin) | |
print_month(mm, last_dict) | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment