Question

Being tempted with Ruby I want to add some syntactic sugar in working with dates in python. How can I implement this method: (3).days.ago() or (4).days.from_now()?

Was it helpful?

Solution

To create a syntax close to what you want, subclass int to add new methods (the built-in int type is unmodifiable so a subclass is the only option for extending integer behaviors). Compute the date offsets using timedelta in the datetime module:

>>> from 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top