Skip to content

Instantly share code, notes, and snippets.

@robertmarriott
Last active October 15, 2021 03:55
Show Gist options
  • Save robertmarriott/b6ee3e36dbe909927322d6b6ae63a7ad to your computer and use it in GitHub Desktop.
Save robertmarriott/b6ee3e36dbe909927322d6b6ae63a7ad to your computer and use it in GitHub Desktop.
Python relative date handling routine. Useful for scheduling daily, weekly and monthly reports.
from datetime import datetime
from dateutil.relativedelta import *
FIRST_DAY = 1
LAST_DAY = 31
TODAY = datetime.combine(datetime.today(), datetime.min.time())
#args_string = '@months=-1,weekday=MO(-1),hour=12'
args_string = '@months=-1,day=LAST_DAY,hour=12'
if args_string[0] == '@':
args = dict(arg.split('=') for arg in args_string[1:].split(','))
args = {key: eval(value) for key, value in args.items()}
fixed_date = TODAY + relativedelta(**args)
print(fixed_date.strftime('%Y-%m-%d %H:%M:%S'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment