Future Date Script
source link: https://bbengfort.github.io/2018/09/future-date/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Future Date Script
This is kind of a dumb post, but it’s something I’m sure I’ll look up in the future. I have a lot of emails where I have to send a date that’s sometime in the future, e.g. six weeks from the end of a class to specify a deadline … I’ve just been opening a Python terminal and importing datetime
and timedelta
but I figured this quick script on the command line would make my life a bit easier:
#!/usr/bin/env python3
import argparse from datetime import datetime, timedelta
try: from dateutil.relativedelta import relativedelta except ImportError: relativedelta = None
DTFMT = "%Y-%m-%d" VALID_KWARGS = frozenset(["years", "months", "weeks", "days"])
def date(s): return datetime.strptime(s, DTFMT)
def today(): return datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
def make_delta(**kwargs): # Filter all the None values from kwargs kwargs = { k: v for k,v in kwargs.items() if v is not None and k in VALID_KWARGS }
if "years" in kwargs or "months" in kwargs: if relativedelta is None: raise ValueError( "python-dateutil is required for future dates with years or months" )
return relativedelta(**kwargs) return timedelta(**kwargs)
if __name__ == "__main__": parser = argparse.ArgumentParser( description="get a date sometime in the future" ) parser.add_argument( "-y", "--years", type=int, default=None, help="number of years in the future", ) parser.add_argument( "-m", "--months", type=int, default=None, help="number of months in the future" ) parser.add_argument( "-w", "--weeks", type=int, default=None, help="number of weeks in the future" ) parser.add_argument( "-d", "--days", type=int, default=None, help="number of days in the future" ) parser.add_argument( "-f", "--format", default=DTFMT, help="output date format in python format string", )
parser.add_argument( "day", type=date, default=today(), nargs="?", help="start date (YYYY-MM-DD) default today" )
args = parser.parse_args() delta = make_delta(years=args.years, months=args.months, weeks=args.weeks, days=args.days) print((args.day + delta).strftime(args.format))
And that’s all there is to it, not very interesting, but something I will probably have in my bin
for the rest of my life.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK