#!/usr/bin/python """Some time utilities for python.""" import sys, re, time, datetime, calendar def intToUtc(now=None): """Return the current UTC time as standard date format.""" timeTuple = time.gmtime(now or time.time()) return time.strftime('%Y-%m-%dT%H:%M:%SZ', timeTuple) r_datenum = re.compile(r'[1-9]\d*|0(?=\D|\Z)') def utcToInt(s): """Convert a Y-M-DTh:m:sZ time into a unixtime int.""" date = r_datenum.findall(s) return calendar.timegm(tuple([int(i) for i in date + list('000')])) def floatToPretty(delta): pass def mdToFloat(s): """Convert a minidelta to a float.""" if s.isdigit(): s += 's' if not s: return float(0) mult = {'s': 1, 'S': 1, 'm': 60, 'h': (60 * 60), 'H': (60 * 60), 'd': (60 * 60 * 24), 'D': (60 * 60 * 24), 'w': (3600 * 24 * 7), 'W': (3600 * 24 * 7), 'f': (3600 * 24 * 7 * 2), 'F': (3600 * 24 * 7 * 2), 'M': (3600 * 24 * 28), 'y': (3600 * 24 * 365.25), 'Y': (3600 * 24 * 365.25)} return float(s[:-1]) * mult.get(s[-1], 1) def deltaToFloat(s): if s.isdigit(): result = float(s) elif s.count(':') == 1: minutes, seconds = tuple(s.split(':')) result = (int(minutes) * 60) + float(seconds) elif s.count(':') == 2: hours, minutes, seconds = tuple(s.split(':')) result = (int(hours) * 3600) + (int(minutes) * 60) + float(seconds) elif (' ' in s) or s: result = reduce(lambda p, q: p + q, [mdToFloat(r) for r in s.split()]) else: result = float(0) return result def next(delta, now=None): """Return current time plus a delta, with a second's accuracy.""" timeNow = datetime.datetime.fromtimestamp(now or time.time()) delta = datetime.timedelta(seconds=deltaToFloat(delta)) projTime = timeNow + delta return projTime.strftime('%Y-%m-%dT%H:%M:%SZ') def lunations(now=None): timeNow = now or time.time() return ((((((timeNow)-978307200)/86400)*850)+5130.5769)/25101) % 1 def main(argv=None): if argv is None: argv = sys.argv[1:] if argv[0] == '--next': print next(argv[1]) elif argv[0] == '--diff': print utcToInt(argv[1]) - utcToInt(argv[2]) elif argv[0] == '--lunations': print lunations() if __name__=="__main__": main()