Example #1
0
    def __init__(
        self,
        year,
        month,
        day,
        hour=0,
        minute=0,
        second=0,
        microsecond=0,
        tzinfo=None,
        **kwargs,
    ):
        if tzinfo is None:
            tzinfo = dateutil_tz.tzutc()
        # detect that tzinfo is a pytz object (issue #626)
        elif (
            isinstance(tzinfo, dt_tzinfo)
            and hasattr(tzinfo, "localize")
            and hasattr(tzinfo, "zone")
            and tzinfo.zone
        ):
            tzinfo = parser.TzinfoParser.parse(tzinfo.zone)
        elif isinstance(tzinfo, str):
            tzinfo = parser.TzinfoParser.parse(tzinfo)

        fold = kwargs.get("fold", 0)

        # use enfold here to cover direct arrow.Arrow init on 2.7/3.5
        self._datetime = dateutil_tz.enfold(
            datetime(year, month, day, hour, minute, second, microsecond, tzinfo),
            fold=fold,
        )
Example #2
0
def test_parse_tzinfos_fold():
    NYC = tz.gettz('America/New_York')
    tzinfos = {'EST': NYC, 'EDT': NYC}

    dt_exp = tz.enfold(datetime(2011, 11, 6, 1, 30, tzinfo=NYC), fold=1)
    dt = parse('2011-11-06T01:30 EST', tzinfos=tzinfos)

    assert dt == dt_exp
    assert dt.tzinfo is dt_exp.tzinfo
    assert getattr(dt, 'fold') == getattr(dt_exp, 'fold')
    assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
Example #3
0
def test_parse_tzinfos_fold():
    NYC = tz.gettz("America/New_York")
    tzinfos = {"EST": NYC, "EDT": NYC}

    dt_exp = tz.enfold(datetime(2011, 11, 6, 1, 30, tzinfo=NYC), fold=1)
    dt = parse("2011-11-06T01:30 EST", tzinfos=tzinfos)

    assert dt == dt_exp
    assert dt.tzinfo is dt_exp.tzinfo
    assert getattr(dt, "fold") == getattr(dt_exp, "fold")
    assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
Example #4
0
def test_parse_tzinfos_fold():
    NYC = tz.gettz('America/New_York')
    tzinfos = {'EST': NYC, 'EDT': NYC}

    dt_exp = tz.enfold(datetime(2011, 11, 6, 1, 30, tzinfo=NYC), fold=1)
    dt = parse('2011-11-06T01:30 EST', tzinfos=tzinfos)

    assert dt == dt_exp
    assert dt.tzinfo is dt_exp.tzinfo
    assert getattr(dt, 'fold') == getattr(dt_exp, 'fold')
    assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
Example #5
0
def test_tzlocal_parse_fold():
    # One manifestion of GH #318
    with TZEnvContext('EST+5EDT,M3.2.0/2,M11.1.0/2'):
        dt_exp = datetime(2011, 11, 6, 1, 30, tzinfo=tz.tzlocal())
        dt_exp = tz.enfold(dt_exp, fold=1)
        dt = parse('2011-11-06T01:30 EST')

        # Because this is ambiguous, kuntil `tz.tzlocal() is tz.tzlocal()`
        # we'll just check the attributes we care about rather than
        # dt == dt_exp
        assert dt.tzname() == dt_exp.tzname()
        assert dt.replace(tzinfo=None) == dt_exp.replace(tzinfo=None)
        assert getattr(dt, 'fold') == getattr(dt_exp, 'fold')
        assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
Example #6
0
def test_tzlocal_parse_fold():
    # One manifestion of GH #318
    with TZEnvContext('EST+5EDT,M3.2.0/2,M11.1.0/2'):
        dt_exp = datetime(2011, 11, 6, 1, 30, tzinfo=tz.tzlocal())
        dt_exp = tz.enfold(dt_exp, fold=1)
        dt = parse('2011-11-06T01:30 EST')

        # Because this is ambiguous, kuntil `tz.tzlocal() is tz.tzlocal()`
        # we'll just check the attributes we care about rather than
        # dt == dt_exp
        assert dt.tzname() == dt_exp.tzname()
        assert dt.replace(tzinfo=None) == dt_exp.replace(tzinfo=None)
        assert getattr(dt, 'fold') == getattr(dt_exp, 'fold')
        assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
def cleaning_daylight_saving_data_with_fold(onebike_datetimes):
    trip_durations = []
    for trip in onebike_datetimes:
        # When the start is later than the end, set the fold to be 1
        if trip['start'] > trip['end']:
            trip['end'] = tz.enfold(trip['end'])
            # Convert to UTC
            start = trip['start'].astimezone(timezone.utc)
            end = trip['end'].astimezone(timezone.utc)

            # Subtract the difference
            trip_length_seconds = (end - start).total_seconds()
            trip_durations.append(trip_length_seconds)

    # Take the shortest trip duration
    print("Shortest trip: " + str(min(trip_durations)))
Example #8
0
    def replace(self, **kwargs):
        """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated
        according to inputs.

        Use property names to set their value absolutely::

            >>> import arrow
            >>> arw = arrow.utcnow()
            >>> arw
            <Arrow [2013-05-11T22:27:34.787885+00:00]>
            >>> arw.replace(year=2014, month=6)
            <Arrow [2014-06-11T22:27:34.787885+00:00]>

        You can also replace the timezone without conversion, using a
        :ref:`timezone expression <tz-expr>`::

            >>> arw.replace(tzinfo=tz.tzlocal())
            <Arrow [2013-05-11T22:27:34.787885-07:00]>

        """

        absolute_kwargs = {}

        for key, value in kwargs.items():

            if key in self._ATTRS:
                absolute_kwargs[key] = value
            elif key in ["week", "quarter"]:
                raise AttributeError(f"setting absolute {key} is not supported")
            elif key not in ["tzinfo", "fold"]:
                raise AttributeError(f'unknown attribute: "{key}"')

        current = self._datetime.replace(**absolute_kwargs)

        tzinfo = kwargs.get("tzinfo")

        if tzinfo is not None:
            tzinfo = self._get_tzinfo(tzinfo)
            current = current.replace(tzinfo=tzinfo)

        fold = kwargs.get("fold")

        # TODO revisit this once we drop support for 2.7/3.5
        if fold is not None:
            current = dateutil_tz.enfold(current, fold=fold)

        return self.fromdatetime(current)
    if tz.datetime_ambiguous(trip['end']):
        print("Ambiguous end at " + str(trip['end']))

############### Exercise ################
# Cleaning daylight saving data with fold
# As we've just discovered, there is a ride in our data set which is being messed up by a Daylight Savings shift. Let's clean up the data set so we actually have a correct minimum ride length. We can use the fact that we know the end of the ride happened after the beginning to fix up the duration messed up by the shift out of Daylight Savings.

# Since Python does not handle tz.enfold() when doing arithmetic, we must put our datetime objects into UTC, where ambiguities have been resolved.

# onebike_datetimes is already loaded and in the right timezone. tz and timezone have been imported. Use tz.UTC for your timezone.

############# Instructions ##############
# Complete the if statement to be true only when a ride's start comes after its end.
# When start is after end, call tz.enfold() on the end so you know it refers to the one after the daylight savings time change.
# After the if statement, convert the start and end to UTC so you can make a proper comparison.

trip_durations = []
for trip in onebike_datetimes:
    # When the start is later than the end, set the fold to be 1
    if trip['start'] > trip['end']:
        trip['end'] = tz.enfold(trip['end'])
    # Convert to UTC
    start = trip['start'].astimezone(tz.UTC)
    end = trip['end'].astimezone(tz.UTC)

    # Subtract the difference
    trip_length_seconds = (end - start).total_seconds()
    trip_durations.append(trip_length_seconds)

# Take the shortest trip duration
print("Shortest trip: " + str(min(trip_durations)))