Skip to content

Instantly share code, notes, and snippets.

@robjwells
Last active January 2, 2016 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robjwells/8370699 to your computer and use it in GitHub Desktop.
Save robjwells/8370699 to your computer and use it in GitHub Desktop.
dayshift: get the date of the next or previous occurrence of a weekday
#!/usr/local/bin/python3
"""
Print the date of the next or last specified weekday.
Usage:
dayshift next <weekday> [--format=<fmt> --inline]
dayshift last <weekday> [--format=<fmt> --inline]
Options:
--format=<fmt>, -f <fmt> A strftime format string
[default: %Y-%m-%d]
--inline, -i Omit trailing newline
"""
from docopt import docopt
from datetime import date, timedelta
WEEKDAYS = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3,
'fri': 4, 'sat': 5, 'sun': 6}
args = docopt(__doc__)
starting_offset = 2 if args['next'] else -2
start_date = date.today() + timedelta(starting_offset)
start_integer = start_date.weekday()
target_integer = WEEKDAYS[args['<weekday>'][:3].lower()]
if args['next']:
offset = target_integer - start_integer
elif args['last']:
offset = start_integer - target_integer
if offset <= 0:
offset += 7
if args['last']:
offset /= -1 # Make the offset negative
target_date = start_date + timedelta(offset)
ending = '' if args['--inline'] else '\n'
print(target_date.strftime(args['--format']), end=ending)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment