Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added replace method on Delorean object #81

Merged
merged 4 commits into from
Sep 16, 2016
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions delorean/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@ def is_datetime_naive(dt):
else:
return False


def is_datetime_instance(dt):
if dt is None:
return
if not isinstance(dt, datetime):
raise ValueError('Please provide a datetime instance to Delorean')


def _move_datetime(dt, direction, delta):
"""
Move datetime given delta by given direction
Expand Down Expand Up @@ -116,18 +118,22 @@ def move_datetime_year(dt, direction, num_shifts):
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta)


def move_datetime_hour(dt, direction, num_shifts):
delta = relativedelta(hours=+num_shifts)
return _move_datetime(dt, direction, delta)


def move_datetime_minute(dt, direction, num_shifts):
delta = relativedelta(minutes=+num_shifts)
return _move_datetime(dt, direction, delta)


def move_datetime_second(dt, direction, num_shifts):
delta = relativedelta(seconds=+num_shifts)
return _move_datetime(dt, direction, delta)


def datetime_timezone(tz):
"""
This method given a timezone returns a localized datetime object.
Expand Down Expand Up @@ -173,7 +179,7 @@ class Delorean(object):
_VALID_SHIFT_DIRECTIONS = ('last', 'next')
_VALID_SHIFT_UNITS = ('second', 'minute', 'hour', 'day', 'week',
'month', 'year', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday','sunday')
'thursday', 'friday', 'saturday', 'sunday')

def __init__(self, datetime=None, timezone=None):
# maybe set timezone on the way in here. if here set it if not
Expand All @@ -186,7 +192,8 @@ def __init__(self, datetime=None, timezone=None):
if isinstance(timezone, tzoffset):
utcoffset = timezone.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)
(utcoffset.microseconds + (
utcoffset.seconds + utcoffset.days * 24 * 3600) * 10 ** 6) / 10 ** 6)
self._tzinfo = pytz.FixedOffset(total_seconds / 60)
elif isinstance(timezone, tzinfo):
self._tzinfo = timezone
Expand All @@ -195,7 +202,7 @@ def __init__(self, datetime=None, timezone=None):
self._dt = localize(datetime, self._tzinfo)
self._tzinfo = self._dt.tzinfo
else:
#TODO(mlew, 2015-08-09):
# TODO(mlew, 2015-08-09):
# Should we really throw an error here, or should this
# default to UTC?)
raise DeloreanInvalidTimezone('Provide a valid timezone')
Expand Down Expand Up @@ -273,7 +280,7 @@ def __getattr__(self, name):

# is the function we are trying to call valid?
if (func_parts[0] not in self._VALID_SHIFT_DIRECTIONS or
func_parts[1] not in self._VALID_SHIFT_UNITS):
func_parts[1] not in self._VALID_SHIFT_UNITS):
return AttributeError

# dispatch our function
Expand Down Expand Up @@ -436,7 +443,6 @@ def start_of_day(self):
"""
return self.midnight


@property
def end_of_day(self):
"""
Expand All @@ -457,7 +463,6 @@ def end_of_day(self):
"""
return self._dt.replace(hour=23, minute=59, second=59, microsecond=999999)


def shift(self, timezone):
"""
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
Expand Down Expand Up @@ -545,6 +550,25 @@ def datetime(self):
"""
return self._dt

def replace(self, **kwargs):
"""
Returns a new Delorean object after applying replace on the
existing datetime object.

.. testsetup::

from datetime import datetime
from delorean import Delorean

.. doctest::

>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')
"""

return Delorean(datetime=self._dt.replace(**kwargs), timezone=self.timezone)

def humanize(self):
"""
Humanize relative to now:
Expand Down
13 changes: 13 additions & 0 deletions docs/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,19 @@ Last Tuesday? Two Tuesdays ago at midnight? No problem.
>>> d.last_tuesday(2).midnight()
datetime.datetime(2013, 1, 8, 0, 0, tzinfo=<UTC>)


Replace Parts
^^^^^^^^^^^^^
Using the `replace` method on `Delorean` objects, we can replace the `hour`, `minute`, `second`, `year` etc
like the the `replace` method on `datetime`.

::

>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')


Truncation
^^^^^^^^^^
Often we dont care how many milliseconds or even seconds that are present in our datetime object. For example it is a nuisance to retrieve `datetimes` that occur in the same minute. You would have to go through the annoying process of replacing zero for the units you don't care for before doing a comparison.
Expand Down
8 changes: 8 additions & 0 deletions tests/delorean_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,5 +773,13 @@ def test_humanize_future(self, mock_now):
do = delorean.Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
self.assertEqual(do.humanize(), 'a day from now')

def test_replace(self):
do = delorean.Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
self.assertEqual(do.replace(hour=8).datetime.hour, 8)
self.assertEqual(do.replace(minute=23).datetime.minute, 23)
self.assertEqual(do.replace(second=45).datetime.second, 45)


Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also like to see a few asserts on the entire datetime object as well and also assuring the timezone is unchanged.


if __name__ == '__main__':
unittest.main()