date - Python: Adding method for number -
being tempted ruby want add syntactic sugar in working dates in python. how can implement method: (3).days.ago() or (4).days.from_now()?
to create syntax close want, subclass int add new methods (the built-in int type unmodifiable subclass option extending integer behaviors). compute date offsets using timedelta in datetime module:
>>> datetime import date, timedelta >>> class int(int): def days_ago(self): return date.today() - timedelta(days=self) def days_from_now(self): return date.today() + timedelta(days=self) >>> int(3).days_ago() datetime.date(2013, 4, 5) >>> int(4).days_from_now() datetime.date(2013, 4, 12)
Comments
Post a Comment