#!/usr/bin/env python """ dtu - A Collecton of Datetime Utilities. License: GPL 2; share and enjoy! Author: Sean B. Palmer, inamidst.com """ import sys, re, datetime # Utility functions r_date = re.compile(r'(\d{4})-(\d{2})-(\d{2})') def date(s): m = r_date.match(s) if not m: raise "ParseError", "Invalid date: %s" % s intify = lambda s: int(s.lstrip('0')) year, month, day = tuple(map(intify, m.groups())) return datetime.datetime(year=year, month=month, day=day) def datenow(): try: return datetime.datetime.now() except ValueError: import time t = time.gmtime() parts = {'year': int(time.strftime('%Y', t)), 'month': int(time.strftime('%m', t)), 'day': int(time.strftime('%d', t)), 'hour': int(time.strftime('%H', t)), 'minute': int(time.strftime('%M', t)), 'second': int(time.strftime('%S', t))} print >> sys.stderr, "Warning: problem generating datenow." return datetime.datetime(**parts) def delta(s): s = ['0', '0'] + s.split(':') secs = int(s.pop().lstrip('0') or '0') mins = int(s.pop().lstrip('0') or '0') hours = int(s.pop().lstrip('0') or '0') return datetime.timedelta(hours=hours, minutes=mins, seconds=secs) def format(t): fmt = '%Y-%m-%d' if t.hour: fmt += ' %H:%M' if t.second: fmt += ':%S' return t.strftime(fmt) # Main commands commands = {} def diff(then, now=None): """diff ? - Return the interval between then and now.""" if now is None: now = datenow() else: now = date(now) then = date(then) if then < now: return '-' + str(now - then) else: return str(then - now) commands['diff'] = diff def hop(step, times=None, now=None): """hop ? ? - Give rpt hops from now given step.""" # @@ Whoo! Lamest documentation evvah! if now is None: now = datenow() else: now = date(now) if times is None: times = 1 else: times = abs(int(times) or 1) if step.startswith('+') or step.startswith('-'): step = int(step) step = datetime.timedelta(days=step) else: step = delta(step) result = [] for i in xrange(times): now = now + step if times > 1: result.append(str(i + 1) + ') ' + format(now)) else: result.append(format(now)) return "\n".join(result) commands['hop'] = hop def info(t): """info - Give information about date.""" t = date(t) result = [t.strftime('%d %B: a %A. Day #%j in the year.')] return "\n".join(result) commands['info'] = info def help(command=None): """help ? - Provide help on a command.""" if command is None: return documentation() if commands.has_key(command): return commands[command].__doc__ elif command == 'help': return help.__doc__ else: return "Can't provide help for command %r." % command commands['help'] = help def documentation(): result = [__doc__] result.append("Valid commands: ") for command in commands.keys(): result.append(" " + commands[command].__doc__) return "\n".join(result).lstrip() def main(args=None): if args is None: args = sys.argv[1:] if (len(args) < 2): print >> sys.stderr, documentation() sys.exit(1) if not commands.has_key(args[0]): print >> sys.stderr, "Unknown command: %s" % args[0] print >> sys.stderr, "Try ./%s help" % sys.argv[0] sys.exit(1) else: print commands[args[0]](*args[1:]) if __name__=="__main__": main()