diff --git a/README.md b/README.md index 0ce417b..80fbbdc 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,27 @@ True + Add [`django-pretty-times`](https://pypi.python.org/pypi/django-pretty-times/0.1.0)-like functionality to allow pretty printing as well +## Pretty Printing + +You can call the `._print()` method on any PrettyTime object to get a pretty-printed string of the time. The method now has an optional parameter `print_stdout` that defaults to `False`. If `print_stdout` is `True`, the method will print the string to the standard output. Otherwise, it will return the string. If the day is today, the function will return or print "today". Here are some examples: + +```python +>>> t(3).days._print() +"3 days" +>>> t(2).hours.from_.now._print() +"2 hours from now" +>>> t(1).week.ago._print() +"1 week ago" +>>> t(3).days._print(print_stdout=True) +3 days +>>> t(2).hours.from_.now._print(print_stdout=True) +2 hours from now +>>> t(1).week.ago._print(print_stdout=True) +1 week ago +>>> t()._print() # if today +"today" +``` + ## Changelog: + 1/28/2018 - Python 3 compatibility + 7/28/2014 - `t()` returns a `datetime.datetime.now()` object diff --git a/prettytime.py b/prettytime.py index e192b74..f24a80b 100644 --- a/prettytime.py +++ b/prettytime.py @@ -100,6 +100,12 @@ class t(object): TIME_LIST = TIME_LIST EXPANDED_TIME_LIST = EXPANDED_TIME_LIST + def _print(self): + if datetime.datetime.today() < self.today: + return str(self.num) + " " + self.attr + " from now" + else: + return str(self.num) + " " + self.attr + " ago" + def __init__(self, num=None): if num is not None: if num >= 0: @@ -139,6 +145,12 @@ def __str__(self): class PrettyDelta(expandeddelta, DeltaMixin): + def _print(self): + if datetime.datetime.today() < self.today: + return str(self.num) + " " + self.attr + " from now" + else: + return str(self.num) + " " + self.attr + " ago" + @property def ago(self): return self._order().today() - self @@ -165,6 +177,12 @@ def in_(self): class PrettyDelta2(expandeddelta, DeltaMixin): + def _print(self): + if datetime.datetime.today() < self.today: + return str(self.num) + " " + self.attr + " from now" + else: + return str(self.num) + " " + self.attr + " ago" + # Will make calculation with (magnitude, order, direction, [magnitude, order, direction]) relativedict = {