Python pendulum.instance() Examples

The following are 30 code examples of pendulum.instance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pendulum , or try the search function .
Example #1
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def _to_string(self, fmt, locale=None):
        """
        Format the instance to a common string format.

        :param fmt: The name of the string format
        :type fmt: string

        :param locale: The locale to use
        :type locale: str or None

        :rtype: str
        """
        if fmt not in self._FORMATS:
            raise ValueError("Format [{}] is not supported".format(fmt))

        fmt = self._FORMATS[fmt]
        if callable(fmt):
            return fmt(self)

        return self.format(fmt, locale=locale) 
Example #2
Source File: test_taskinstance.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_next_retry_datetime_short_intervals(self):
        delay = datetime.timedelta(seconds=1)
        max_delay = datetime.timedelta(minutes=60)

        dag = models.DAG(dag_id='fail_dag')
        task = BashOperator(
            task_id='task_with_exp_backoff_and_short_time_interval',
            bash_command='exit 1',
            retries=3,
            retry_delay=delay,
            retry_exponential_backoff=True,
            max_retry_delay=max_delay,
            dag=dag,
            owner='airflow',
            start_date=timezone.datetime(2016, 2, 1, 0, 0, 0))
        ti = TI(
            task=task, execution_date=DEFAULT_DATE)
        ti.end_date = pendulum.instance(timezone.utcnow())

        date = ti.next_retry_datetime()
        # between 1 * 2^0.5 and 1 * 2^1 (15 and 30)
        period = ti.end_date.add(seconds=15) - ti.end_date.add(seconds=1)
        self.assertTrue(date in period) 
Example #3
Source File: taskinstance.py    From airflow with Apache License 2.0 6 votes vote down vote up
def are_dependents_done(self, session=None):
        """
        Checks whether the immediate dependents of this task instance have succeeded or have been skipped.
        This is meant to be used by wait_for_downstream.

        This is useful when you do not want to start processing the next
        schedule of a task until the dependents are done. For instance,
        if the task DROPs and recreates a table.
        """
        task = self.task

        if not task.downstream_task_ids:
            return True

        ti = session.query(func.count(TaskInstance.task_id)).filter(
            TaskInstance.dag_id == self.dag_id,
            TaskInstance.task_id.in_(task.downstream_task_ids),
            TaskInstance.execution_date == self.execution_date,
            TaskInstance.state.in_([State.SKIPPED, State.SUCCESS]),
        )
        count = ti[0][0]
        return count == len(task.downstream_task_ids) 
Example #4
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def __rsub__(self, other):
        if not isinstance(other, datetime.datetime):
            return NotImplemented

        if not isinstance(other, self.__class__):
            if other.tzinfo is None:
                other = pendulum.naive(
                    other.year,
                    other.month,
                    other.day,
                    other.hour,
                    other.minute,
                    other.second,
                    other.microsecond,
                )
            else:
                other = pendulum.instance(other)

        return self.diff(other, False) 
Example #5
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def __sub__(self, other):
        if isinstance(other, datetime.timedelta):
            return self._subtract_timedelta(other)

        if not isinstance(other, datetime.datetime):
            return NotImplemented

        if not isinstance(other, self.__class__):
            if other.tzinfo is None:
                other = pendulum.naive(
                    other.year,
                    other.month,
                    other.day,
                    other.hour,
                    other.minute,
                    other.second,
                    other.microsecond,
                )
            else:
                other = pendulum.instance(other)

        return other.diff(self, False) 
Example #6
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def average(self, dt=None):
        """
        Modify the current instance to the average
        of a given instance (default now) and the current instance.

        :type dt: DateTime or datetime

        :rtype: DateTime
        """
        if dt is None:
            dt = self.now(self.tz)

        diff = self.diff(dt, False)
        return self.add(
            microseconds=(diff.in_seconds() * 1000000 + diff.microseconds) // 2
        ) 
Example #7
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def on(self, year, month, day):
        """
        Returns a new instance with the current date set to a different date.

        :param year: The year
        :type year: int

        :param month: The month
        :type month: int

        :param day: The day
        :type day: int

        :rtype: DateTime
        """
        return self.set(year=int(year), month=int(month), day=int(day)) 
Example #8
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def first_of(self, unit, day_of_week=None):
        """
        Returns an instance set to the first occurrence
        of a given day of the week in the current unit.
        If no day_of_week is provided, modify to the first day of the unit.
        Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY.

        Supported units are month, quarter and year.

        :param unit: The unit to use
        :type unit: str

        :type day_of_week: int or None

        :rtype: DateTime
        """
        if unit not in ["month", "quarter", "year"]:
            raise ValueError('Invalid unit "{}" for first_of()'.format(unit))

        return getattr(self, "_first_of_{}".format(unit))(day_of_week) 
Example #9
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def end_of(self, unit):
        """
        Returns a copy of the instance with the time reset
        with the following rules:

        * second: microsecond set to 999999
        * minute: second set to 59 and microsecond set to 999999
        * hour: minute and second set to 59 and microsecond set to 999999
        * day: time to 23:59:59.999999
        * week: date to last day of the week and time to 23:59:59.999999
        * month: date to last day of the month and time to 23:59:59.999999
        * year: date to last day of the year and time to 23:59:59.999999
        * decade: date to last day of the decade and time to 23:59:59.999999
        * century: date to last day of century and time to 23:59:59.999999

        :param unit: The unit to reset to
        :type unit: str

        :rtype: DateTime
        """
        if unit not in self._MODIFIERS_VALID_UNITS:
            raise ValueError('Invalid unit "%s" for end_of()' % unit)

        return getattr(self, "_end_of_%s" % unit)() 
Example #10
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def at(self, hour, minute=0, second=0, microsecond=0):
        """
        Returns a new instance with the current time to a different time.

        :param hour: The hour
        :type hour: int

        :param minute: The minute
        :type minute: int

        :param second: The second
        :type second: int

        :param microsecond: The microsecond
        :type microsecond: int

        :rtype: DateTime
        """
        return self.set(
            hour=hour, minute=minute, second=second, microsecond=microsecond
        ) 
Example #11
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def start_of(self, unit):
        """
        Returns a copy of the instance with the time reset
        with the following rules:

        * second: microsecond set to 0
        * minute: second and microsecond set to 0
        * hour: minute, second and microsecond set to 0
        * day: time to 00:00:00
        * week: date to first day of the week and time to 00:00:00
        * month: date to first day of the month and time to 00:00:00
        * year: date to first day of the year and time to 00:00:00
        * decade: date to first day of the decade and time to 00:00:00
        * century: date to first day of century and time to 00:00:00

        :param unit: The unit to reset to
        :type unit: str

        :rtype: DateTime
        """
        if unit not in self._MODIFIERS_VALID_UNITS:
            raise ValueError('Invalid unit "{}" for start_of()'.format(unit))

        return getattr(self, "_start_of_{}".format(unit))() 
Example #12
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def is_anniversary(self, dt=None):
        """
        Check if its the anniversary.
        Compares the date/month values of the two dates.

        :rtype: bool
        """
        if dt is None:
            dt = self.now(self.tz)

        instance = pendulum.instance(dt)

        return (self.month, self.day) == (instance.month, instance.day)

    # the additional method for checking if today is the anniversary day
    # the alias is provided to start using a new name and keep the backward compatibility
    # the old name can be completely replaced with the new in one of the future versions 
Example #13
Source File: taskinstance.py    From airflow with Apache License 2.0 6 votes vote down vote up
def filter_for_tis(
        tis: Iterable[Union["TaskInstance", TaskInstanceKeyType]]
    ) -> Optional[BooleanClauseList]:
        """Returns SQLAlchemy filter to query selected task instances"""
        TI = TaskInstance
        if not tis:
            return None
        if all(isinstance(t, tuple) for t in tis):
            filter_for_tis = ([and_(TI.dag_id == dag_id,
                                    TI.task_id == task_id,
                                    TI.execution_date == execution_date)
                               for dag_id, task_id, execution_date, _ in tis])
            return or_(*filter_for_tis)
        if all(isinstance(t, TaskInstance) for t in tis):
            filter_for_tis = ([and_(TI.dag_id == ti.dag_id,  # type: ignore
                                    TI.task_id == ti.task_id,  # type: ignore
                                    TI.execution_date == ti.execution_date)  # type: ignore
                               for ti in tis])
            return or_(*filter_for_tis)

        raise TypeError("All elements must have the same type: `TaskInstance` or `TaskInstanceKey`.")


# State of the task instance.
# Stores string version of the task state. 
Example #14
Source File: test_dom.py    From pycron with MIT License 6 votes vote down vote up
def test_dom():
    def run(now):
        assert pycron.is_now('* * * * *', now)
        assert pycron.is_now('* * 18 * *', now)
        assert pycron.is_now('* * */6 * *', now)
        assert pycron.is_now('* * 1,16,18 * *', now)
        assert pycron.is_now('* * 19 * *', now) is False
        assert pycron.is_now('* * */4 * *', now) is False
        assert pycron.is_now('* * 1,16 * *', now) is False
        assert pycron.is_now('* * 1,16 * *', now) is False
        assert pycron.is_now('* * 1-20 * *', now)
        assert pycron.is_now('* * 20-31 * *', now) is False

    now = datetime(2015, 6, 18, 16, 7)
    run(now)
    run(now.replace(tzinfo=utc))
    run(pendulum.instance(now))
    run(arrow.get(now))
    run(udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=now, timezone='UTC').datetime) 
Example #15
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def _subtract_timedelta(self, delta):
        """
        Remove timedelta duration from the instance.

        :param delta: The timedelta instance
        :type delta: pendulum.Duration or datetime.timedelta

        :rtype: DateTime
        """
        if isinstance(delta, pendulum.Duration):
            return self.subtract(
                years=delta.years, months=delta.months, seconds=delta._total
            )

        return self.subtract(seconds=delta.total_seconds())

    # DIFFERENCES 
Example #16
Source File: datetime.py    From pendulum with MIT License 6 votes vote down vote up
def closest(self, dt1, dt2, *dts):
        """
        Get the farthest date from the instance.

        :type dt1: datetime.datetime
        :type dt2: datetime.datetime
        :type dts: list[datetime.datetime,]

        :rtype: DateTime
        """
        dt1 = pendulum.instance(dt1)
        dt2 = pendulum.instance(dt2)
        dts = [dt1, dt2] + [pendulum.instance(x) for x in dts]
        dts = [(abs(self - dt), dt) for dt in dts]

        return min(dts)[1] 
Example #17
Source File: test_has_been.py    From pycron with MIT License 6 votes vote down vote up
def test_days():
    def run(since, now):
        assert pycron.has_been('* * * * *', since, now)
        assert pycron.has_been('* * 0 * *', since, now) is False
        assert pycron.has_been('* * 1 * *', since, now)
        assert pycron.has_been('* * 2 * *', since, now)
        assert pycron.has_been('* * 3 * *', since, now)
        assert pycron.has_been('* * 4 * *', since, now) is False

    since = datetime(2015, 6, 1, 0, 0)
    now = datetime(2015, 6, 3, 0, 0)
    run(since, now)
    run(since.replace(tzinfo=utc), now.replace(tzinfo=utc))
    run(pendulum.instance(since), pendulum.instance(now))
    run(arrow.get(since), arrow.get(now))
    run(udatetime.from_string(since.isoformat()), udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=since, timezone='UTC').datetime, Delorean(datetime=now, timezone='UTC').datetime) 
Example #18
Source File: test_has_been.py    From pycron with MIT License 6 votes vote down vote up
def test_hours():
    def run(since, now):
        assert pycron.has_been('* * * * *', since, now)
        assert pycron.has_been('* 0 * * *', since, now) is False
        assert pycron.has_been('* 1 * * *', since, now)
        assert pycron.has_been('* 2 * * *', since, now)
        assert pycron.has_been('* 3 * * *', since, now)
        assert pycron.has_been('* 4 * * *', since, now) is False

    since = datetime(2015, 6, 18, 1, 0)
    now = datetime(2015, 6, 18, 3, 0)
    run(since, now)
    run(since.replace(tzinfo=utc), now.replace(tzinfo=utc))
    run(pendulum.instance(since), pendulum.instance(now))
    run(arrow.get(since), arrow.get(now))
    run(udatetime.from_string(since.isoformat()), udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=since, timezone='UTC').datetime, Delorean(datetime=now, timezone='UTC').datetime) 
Example #19
Source File: test_has_been.py    From pycron with MIT License 6 votes vote down vote up
def test_minutes():
    def run(since, now):
        assert pycron.has_been('* * * * *', since, now)
        assert pycron.has_been('0 * * * *', since, now) is False
        assert pycron.has_been('1 * * * *', since, now)
        assert pycron.has_been('2 * * * *', since, now)
        assert pycron.has_been('3 * * * *', since, now)
        assert pycron.has_been('4 * * * *', since, now) is False

    since = datetime(2015, 6, 18, 0, 1)
    now = datetime(2015, 6, 18, 0, 3)
    run(since, now)
    run(since.replace(tzinfo=utc), now.replace(tzinfo=utc))
    run(pendulum.instance(since), pendulum.instance(now))
    run(arrow.get(since), arrow.get(now))
    run(udatetime.from_string(since.isoformat()), udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=since, timezone='UTC').datetime, Delorean(datetime=now, timezone='UTC').datetime) 
Example #20
Source File: test_month.py    From pycron with MIT License 6 votes vote down vote up
def test_parser():
    def run(now):
        assert pycron.is_now('* * * * *', now)
        assert pycron.is_now('* * * 6 *', now)
        assert pycron.is_now('* * * */2 *', now)
        assert pycron.is_now('* * * 1,4,6,12 *', now)
        assert pycron.is_now('* * * 5 *', now) is False
        assert pycron.is_now('* * * */5 *', now) is False
        assert pycron.is_now('* * * 1,4,12 *', now) is False
        assert pycron.MONTH_CHOICES[now.month - 1][1] == 'June'
        assert pycron.is_now('* * * 5-8 *', now)
        assert pycron.is_now('* * * 8-10 *', now) is False

    now = datetime(2015, 6, 18, 16, 7)
    run(now)
    run(now.replace(tzinfo=utc))
    run(pendulum.instance(now))
    run(arrow.get(now))
    run(udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=now, timezone='UTC').datetime) 
Example #21
Source File: test_hour.py    From pycron with MIT License 6 votes vote down vote up
def test_hour():
    def run(now):
        assert pycron.is_now('* * * * *', now)
        assert pycron.is_now('* 16 * * *', now)
        assert pycron.is_now('* */4 * * *', now)
        assert pycron.is_now('*/7 16 * * *', now)
        assert pycron.is_now('*/7 */8 * * *', now)
        assert pycron.is_now('* 2,8,16 * * *', now)
        assert pycron.is_now('* */9 * * *', now) is False
        assert pycron.is_now('* */5 * * *', now) is False
        assert pycron.is_now('*/3 */4 * * *', now) is False
        assert pycron.is_now('3 16 * * *', now) is False
        assert pycron.is_now('*/8 */3 * * *', now) is False
        assert pycron.is_now('* 2,8 * * *', now) is False
        assert pycron.is_now('* 16-20 * * *', now)
        assert pycron.is_now('* 0-10 * * *', now) is False

    now = datetime(2015, 6, 18, 16, 7)
    run(now)
    run(now.replace(tzinfo=utc))
    run(pendulum.instance(now))
    run(arrow.get(now))
    run(udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=now, timezone='UTC').datetime) 
Example #22
Source File: test_minute.py    From pycron with MIT License 6 votes vote down vote up
def test_minute_ranges():
    for i in range(1, 59, 2):
        now = datetime(2015, 6, 18, 0, i)
        assert pycron.is_now('1-59/2 * * * *', now)
        assert pycron.is_now('1-59/2 * * * *', now.replace(tzinfo=utc))
        assert pycron.is_now('1-59/2 * * * *', pendulum.instance(now))
        assert pycron.is_now('1-59/2 * * * *', arrow.get(now))
        assert pycron.is_now('1-59/2 * * * *', udatetime.from_string(now.isoformat()))
        assert pycron.is_now('1-59/2 * * * *', Delorean(datetime=now, timezone='UTC').datetime)

    for i in range(0, 59, 2):
        now = datetime(2015, 6, 18, 0, i)
        assert pycron.is_now('1-59/2 * * * *', now) is False
        assert pycron.is_now('1-59/2 * * * *', now.replace(tzinfo=utc)) is False
        assert pycron.is_now('1-59/2 * * * *', pendulum.instance(now)) is False
        assert pycron.is_now('1-59/2 * * * *', arrow.get(now)) is False
        assert pycron.is_now('1-59/2 * * * *', udatetime.from_string(now.isoformat())) is False
        assert pycron.is_now('1-59/2 * * * *', Delorean(datetime=now, timezone='UTC').datetime) is False 
Example #23
Source File: check.py    From heartbeats with MIT License 6 votes vote down vote up
def process_at_service(self, service):
        """
        当 当前时间 > at时,看[at, at + grace]之间是否有上报的数据
        """
        latest_ping = self.get_last_ping(service)
        if not latest_ping:
            return

        at = pendulum.parse(service.value, tz=settings.TIME_ZONE).in_timezone('UTC')
        last_created = pendulum.instance(latest_ping.created)
        now = pendulum.now(tz='UTC')

        if now < at.add(minutes=int(service.grace)):
            return
        if last_created < at:
            self.notify(service, now) 
Example #24
Source File: test_dow.py    From pycron with MIT License 6 votes vote down vote up
def test_day_matching():
    def run(now):
        for i in range(0, 7):
            # Test day matching from Sunday onwards...
            now += timedelta(days=1)
            assert pycron.is_now('* * * * %i' % (i), now)
            # Test weekdays
            assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
            assert pycron.is_now('* * * * 1-5', now) is (True if i not in [0, 6] else False)
            assert pycron.is_now('* * * * 1,2,3,4-5', now) is (True if i not in [0, 6] else False)
            # Test weekends
            assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False)

    now = datetime(2015, 6, 20, 16, 7)
    run(now)
    run(now.replace(tzinfo=utc))
    run(pendulum.instance(now))
    run(arrow.get(now))
    run(udatetime.from_string(now.isoformat()))
    run(Delorean(datetime=now, timezone='UTC').datetime) 
Example #25
Source File: taskinstance.py    From airflow with Apache License 2.0 6 votes vote down vote up
def construct_task_instance(self, session=None, lock_for_update=False) -> TaskInstance:
        """
        Construct a TaskInstance from the database based on the primary key

        :param session: DB session.
        :param lock_for_update: if True, indicates that the database should
            lock the TaskInstance (issuing a FOR UPDATE clause) until the
            session is committed.
        :return: the task instance constructed
        """

        qry = session.query(TaskInstance).filter(
            TaskInstance.dag_id == self._dag_id,
            TaskInstance.task_id == self._task_id,
            TaskInstance.execution_date == self._execution_date)

        if lock_for_update:
            ti = qry.with_for_update().first()
        else:
            ti = qry.first()
        return ti 
Example #26
Source File: datetime.py    From pendulum with MIT License 5 votes vote down vote up
def to_rfc1123_string(self):
        """
        Format the instance as RFC 1123.

        :rtype: str
        """
        return self._to_string("rfc1123") 
Example #27
Source File: datetime.py    From pendulum with MIT License 5 votes vote down vote up
def to_rfc850_string(self):
        """
        Format the instance as RFC 850.

        :rtype: str
        """
        return self._to_string("rfc850") 
Example #28
Source File: datetime.py    From pendulum with MIT License 5 votes vote down vote up
def to_w3c_string(self):
        """
        Format the instance as W3C.

        :rtype: str
        """
        return self._to_string("w3c") 
Example #29
Source File: datetime.py    From pendulum with MIT License 5 votes vote down vote up
def to_rfc822_string(self):
        """
        Format the instance as RFC 822.

        :rtype: str
        """
        return self._to_string("rfc822") 
Example #30
Source File: datetime.py    From pendulum with MIT License 5 votes vote down vote up
def to_iso8601_string(self):
        """
        Format the instance as ISO 8601.

        :rtype: str
        """
        string = self._to_string("iso8601")

        if self.tz and self.tz.name == "UTC":
            string = string.replace("+00:00", "Z")

        return string