def test_round_datetime(self): # get current datetime dt = datetime.now() for unit in Period.UNITS: for i in range(0, 5): period = Period(**{unit: i}) round_dt = period.round_datetime(dt) value = getattr(dt, unit, None) if value is not None: value_to_set = value + 1 if unit != Period.YEAR else 2000 period.unit_values[unit] = value_to_set round_dt = period.round_datetime(dt) round_value = getattr(round_dt, unit) if round_value is not None: if unit is Period.YEAR: self.assertEqual(round_value, 2000) elif unit is Period.DAY: month = dt.month - 1 if month == 0: month = 12 _, monthday = monthrange(dt.year, month) self.assertEqual(round_value, monthday) elif unit is Period.MONTH: self.assertEqual(round_value, 12) else: self.assertEqual(round_value, 0) if Period.MICROSECOND is not unit: normalized_dt = period.round_datetime(dt, normalize=True) for _unit in Period.UNITS[0:Period.UNITS.index(unit) - 1]: if _unit is not Period.WEEK: normalized_dt_unit = getattr(normalized_dt, _unit) if _unit is Period.MONTH or _unit is Period.DAY: self.assertEqual(normalized_dt_unit, 1) else: self.assertEqual(normalized_dt_unit, 0)
def test_round_datetime(self, ts=None): now = datetime.now() if ts is None else datetime.utcfromtimestamp(ts) for unitindex, unit in enumerate(Period.UNITS): if unit in (Period.MONTH, Period.YEAR): continue for i in range(0, 5): period = Period(**{unit: i}) round_dt = period.round_datetime(now) round_value = getattr(round_dt, unit, None) unitval = getattr(now, unit, None) if unitval is not None: if unit is Period.DAY: roundday = unitval - (unitval % max(1, i)) if roundday <= 0: month = now.month - 1 if month == 0: month = 12 _, roundday = monthrange(now.year, month) self.assertEqual(round_value, roundday) else: maxunitval = Period.MAX_UNIT_VALUES[unitindex] rval = (unitval - (unitval % max(1, i))) % maxunitval self.assertEqual(rval, round_value) for _unit in Period.UNITS[:max(0, unitindex - 1)]: _round_value = getattr(round_dt, _unit, None) if _unit in (Period.MONTH, Period.DAY): _round_value -= 1 self.assertFalse(_round_value)