Source

scripts / datedelta.py

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

2011 (c) Andrey Mikhaylenko

Usage::

    $ python datedelta.py today +2w
    2011-05-21
    $ python datedelta.py 2011-01-02 -4d
    2010-12-29

.. note::

    In some cases you can do without this script::

        $ date -d "2 weeks"
        $ date -d "4 days ago" +%Y-%m-%d

"""
import sys
from datetime import datetime, timedelta


def get_datetime(string):
    if string in ('now', 'today'):
        return datetime.now()
    else:
        return datetime.strptime(string, '%Y-%m-%d')

def get_timedelta(string):
    "1w → 1 week; 2d → 2 days, 3m → 3 months, etc."
    PERIODS = {
        'd': 1,
        'w': 7,
        'm': 30,
    }
    num = string[:-1]
    period = string[-1]
    k = PERIODS[period]
    days = int(num) * k
    return timedelta(days=days)

def main(raw_start, raw_delta):
    start = get_datetime(raw_start)

    if raw_delta.startswith('-'):
        # substract
        raw_delta = raw_delta[1:]
        return start - get_timedelta(raw_delta)
    else:
        # add
        if raw_delta.startswith('+'):
            raw_delta = raw_delta[1:]
        return start + get_timedelta(raw_delta)

if __name__=='__main__':
    raw_start = sys.argv[1]
    raw_delta = sys.argv[2]

    print main(raw_start, raw_delta).strftime('%Y-%m-%d')
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.