scripts / timedelta.py

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""CLI utility for time delta calculation.

2010, 2011 (c) Andrey Mikhaylenko

Use cases:

``td 12:00 00:10 00:15 01:05``
    12:00, 12:10, 12:15, 13:05
``td 12:00 10 15 105``
    12:00, 12:10, 12:15, 13:05 (same as above)
``td now -5``
    5 minutes before now
``td now-50 5 15 30``
    (now - 50 min) + 5, 15, 30 minutes

"""
import sys
from datetime import datetime, timedelta, time


def parse_time(string):
    """
    Returns a datetime.time object and a boolean that tells whether given time
    should be substracted from the start time.

        >>> parse_time('20')
        (time(0, 20), False)
        >>> parse_time('-1:35')
        (time(1, 35), True)
        >>> parse_time('now')
        datetime.now().time()
        >>> parse_time('now-5')
        datetime.now().time() - timedelta(minutes=5)

    """
    substract = False

    if string == 'now':
        return datetime.now().time(), substract

    if string.startswith('now-'):
        # "now-150"
        now = datetime.now()
        _, substring = string.split('-')
        delta, _ = parse_time(substring)
        start = now - timedelta(hours=delta.hour, minutes=delta.minute)
        return start.time(), substract

    if string.startswith('-'):
        # "-2:58"
        substract = True
        string = string[1:]

    # "19:35"
    if ':' in string:
        hours, minutes = string.split(':')
    else:
        if len(string) <= 2:
            # "35" -> 00:35
            hours, minutes = 0, string
        else:
            hours, minutes = string[:-2], string[-2:]

    return time(int(hours), int(minutes)), substract

def calc_delta(start_str, *delta_strs):
    """
    >>> calc_delta('19:21', '3')
    [datetime.datetime(2010, 9, 20, 19, 24)]
    >>> calc_delta('19:21', '30')
    [datetime.datetime(2010, 9, 20, 19, 51)]
    >>> calc_delta('19:21', '1:30')
    [datetime.datetime(2010, 9, 20, 20, 51)]
    >>> calc_delta('19:21', '1:30', '135')
    [datetime.datetime(2010, 9, 20, 20, 51),
     datetime.datetime(2010, 9, 20, 20, 56)]

    """
    today = datetime.today()
    start_time, substract = parse_time(start_str)
    assert not substract, 'start time cannot be negative'
    start = datetime.combine(today, start_time)
    for delta_str in delta_strs:
        delta_time, substract = parse_time(delta_str)
        delta = timedelta(seconds=60*(delta_time.minute + 60*delta_time.hour))
        checkpoint = start - delta if substract else start + delta
        yield delta, checkpoint

if __name__=='__main__':
    #for delta, dt in calc_delta(*sys.argv[1:]):
    start = sys.argv[1]
    deltas = ['0'] + sys.argv[2:]
    for delta, dt in calc_delta(start, *deltas):
        print u'Δ {delta}  →  {dt}'.format(**locals())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.