예제 #1
0
    def shift(self, **kwargs):
        """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated
        according to inputs.

        Use pluralized property names to relatively shift their current value:

        >>> import arrow
        >>> arw = arrow.utcnow()
        >>> arw
        <Arrow [2013-05-11T22:27:34.787885+00:00]>
        >>> arw.shift(years=1, months=-1)
        <Arrow [2014-04-11T22:27:34.787885+00:00]>

        Day-of-the-week relative shifting can use either Python's weekday numbers
        (Monday = 0, Tuesday = 1 .. Sunday = 6) or using dateutil.relativedelta's
        day instances (MO, TU .. SU).  When using weekday numbers, the returned
        date will always be greater than or equal to the starting date.

        Using the above code (which is a Saturday) and asking it to shift to Saturday:

        >>> arw.shift(weekday=5)
        <Arrow [2013-05-11T22:27:34.787885+00:00]>

        While asking for a Monday:

        >>> arw.shift(weekday=0)
        <Arrow [2013-05-13T22:27:34.787885+00:00]>

        """

        relative_kwargs = {}
        additional_attrs = ["weeks", "quarters", "weekday"]

        for key, value in kwargs.items():

            if key in self._ATTRS_PLURAL or key in additional_attrs:
                relative_kwargs[key] = value
            else:
                raise AttributeError(
                    "Invalid shift time frame. Please select one of the following: {}.".format(
                        ", ".join(self._ATTRS_PLURAL + additional_attrs)
                    )
                )

        # core datetime does not support quarters, translate to months.
        relative_kwargs.setdefault("months", 0)
        relative_kwargs["months"] += (
            relative_kwargs.pop("quarters", 0) * self._MONTHS_PER_QUARTER
        )

        current = self._datetime + relativedelta(**relative_kwargs)

        if not dateutil_tz.datetime_exists(current):
            current = dateutil_tz.resolve_imaginary(current)

        return self.fromdatetime(current)
예제 #2
0
def walltimedelta(start, end, tz=None) -> datetime.timedelta:
    """
    Time period in wall time. DST offsets are taken into account.
    see https://github.com/dateutil/dateutil/issues/1039#issue-613403091
    """

    if tz is None:
        if start.tzinfo is None or end.tzinfo is None:
            raise ValueError('Some datetime is naive and no time zone provided.')
        elif start.tzinfo is not end.tzinfo:
            raise ValueError('Datetimes are on different time zones.')
    else:
        start = start.replace(tzinfo=tz)
        end = end.replace(tzinfo=tz)

    start = resolve_imaginary(start).astimezone(UTC)
    end = resolve_imaginary(end).astimezone(UTC)

    return end - start
예제 #3
0
    def _add_test_items_for_samples(
        self,
        items_map: Dict[int, TestItem],
        tz: Any,
    ) -> None:
        """Add a TestItem for each month from start_year to until_year."""

        for year in range(self.start_year, self.until_year):
            for month in range(1, 13):
                # Add a sample test point on the first of each month
                dt_local = resolve_imaginary(
                    datetime(year, month, 1, 0, 0, 0, tzinfo=tz))
                item = self._create_test_item(dt_local, 'S')
                self._add_test_item(items_map, item)

            # Add a sample test point at the end of the year.
            dt_local = resolve_imaginary(
                datetime(year, 12, 31, 23, 59, 0, tzinfo=tz))
            item = self._create_test_item(dt_local, 'Y')
            self._add_test_item(items_map, item)
예제 #4
0
    def shift(self, **kwargs):
        relatives = {}
        addattrs = ['weeks', 'quarters', 'weekday']
        for k, v in kwargs.items():
            if k in self._ATTR_MAP or k in addattrs:
                relatives[k] = v
            elif k in self._ATTRS + ['week', 'quarter']:
                relatives[f'{k}s'] = v
            else:
                supported = ', '.join(self._ATTRS_PLURAL + addattrs)
                raise ValueError(
                    f'timeframe not supported: {k!r} not in {supported}')

        relatives.setdefault('months', 0)
        relatives['months'] += relatives.pop('quarters', 0) * 3

        current = self._dt + relativedelta(**relatives)
        if not dtz.datetime_exists(current):
            current = dtz.resolve_imaginary(current)

        return self.fromdatetime(current, tzinfo=self.tzinfo)