Python datetime.timedelta() Examples

The following are code examples for showing how to use datetime.timedelta(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: odorik   Author: nijel   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def get_interval(self):
        """Return interval based on passed flags."""
        now = datetime.now()

        if self.args.start_date and self.args.end_date:
            if self.args.start_date >= self.args.end_date:
                raise CommandError(
                    'Starting date has to be earlier than ending!'
                )
            return (self.args.start_date, self.args.end_date)
        elif self.args.start_date:
            return (self.args.start_date, now)
        elif self.args.end_date:
            raise CommandError('Can not set ending date without start!')

        if self.args.last_month:
            # Get last day of previous month
            now = now.replace(day=1) - timedelta(days=1)
            # Set to midnight
            now = now.replace(hour=23, minute=59, second=59)

        # Fallback to this month
        return (datetime(now.year, now.month, 1), now) 
Example 2
Project: webnull   Author: macrael   File: test_pretty_date.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_delta_tests():
    test_deltas = {
        '5min': { 'delta': datetime.timedelta(minutes=5), 'pretty': '1:40 PM' },
        '5.5min': { 'delta': datetime.timedelta(minutes=5, seconds=32), 'pretty': '1:40 PM' },
        '10min': { 'delta': datetime.timedelta(minutes=10, seconds=2), 'pretty': '1:45 PM' },
        '2hours': { 'delta': datetime.timedelta(hours=2, seconds=4), 'pretty': '3:35 PM' },
        '14hours': { 'delta': datetime.timedelta(hours=14, seconds=2), 'pretty': '3:35 AM' },
        '24hours': { 'delta': datetime.timedelta(hours=24, minutes=10, seconds=2), 'pretty': 'tomorrow at 1:45 PM' },
        '2days': { 'delta': datetime.timedelta(days=2, minutes=10, seconds=2), 'pretty': 'Sunday at 1:45 PM' },
        '6days': { 'delta': datetime.timedelta(days=6, minutes=10, seconds=2), 'pretty': 'Thursday at 1:45 PM' },
        '7days': { 'delta': datetime.timedelta(days=7, minutes=10, seconds=2), 'pretty': 'Friday the 31st at 1:45 PM' },
        '8days': { 'delta': datetime.timedelta(days=8, minutes=10, seconds=2), 'pretty': 'April 1st at 1:45 PM' },
        '8years': { 'delta': datetime.timedelta(weeks=8*52, days=8, minutes=10, seconds=2), 'pretty': 'March 22nd 2025 at 1:45 PM' },
    }

    for label in test_deltas.keys():
        new_test = generate_test(test_deltas[label]['delta'], test_deltas[label]['pretty'])
        test_name = 'test_' + label
        setattr(PrettyDateTests, test_name, new_test) 
Example 3
Project: tom-bot   Author: maartenberg   File: datefinder.py    MIT License 6 votes vote down vote up
def find_timedelta(text):
    '''
    (Attempts to) Find the first readable duration in a text and return it as a datetime.

    Argument: the text to search. The regex is horrible, so take care.
    Returns a timedelta, zero-length if no matches.
    '''
    matches = REGEX.findall(text)
    match = None
    for res in matches:
        if any(res):
            match = res
            break
    if not match:
        raise ValueError('Could not extract duration!')
    years = int(match[1]) if match[1] else 0 # in tdays
    weeks = int(match[5]) if match[5] else 0 # in tdays
    days = int(match[9]) if match[9] else 0 # in tdays
    tdays = days + 7 * weeks + 365 * years
    hours = int(match[13]) if match[13] else 0 # passed
    minutes = int(match[17]) if match[17] else 0 # passed
    seconds = int(match[21]) if match[21] else 0 # passed
    result = timedelta(
        days=tdays, hours=hours, minutes=minutes, seconds=seconds)
    return result 
Example 4
Project: tom-bot   Author: maartenberg   File: datefinder.py    MIT License 6 votes vote down vote up
def find_first_time(text):
    '''
    Find the first occurrence of a clock time, return as datetime in today or tomorrow.
    Raises ValueError if no time is found.
    '''
    match = CLOCK_REGEX.search(text)
    if not match:
        raise ValueError('No time found!')
    hour = int(match.group('hour'))
    minute = int(match.group('minute')) if match.group('minute') else 0
    second = int(match.group('second')) if match.group('second') else 0
    result = datetime.datetime.now().replace(
        hour=hour, minute=minute, second=second)
    if result < datetime.datetime.now():
        result = result + datetime.timedelta(days=1)
    return result 
Example 5
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def itermonthdates(self, year, month):
        """
        Return an iterator for one month. The iterator will yield datetime.date
        values and will always iterate through complete weeks, so it will yield
        dates outside the specified month.
        """
        date = datetime.date(year, month, 1)
        # Go back to the beginning of the week
        days = (date.weekday() - self.firstweekday) % 7
        date -= datetime.timedelta(days=days)
        oneday = datetime.timedelta(days=1)
        while True:
            yield date
            try:
                date += oneday
            except OverflowError:
                # Adding one day could fail after datetime.MAXYEAR
                break
            if date.month != month and date.weekday() == self.firstweekday:
                break 
Example 6
Project: ecscale   Author: omerxx   File: ecscale.py    MIT License 6 votes vote down vote up
def cluster_memory_reservation(cwClient, clusterName):
    # Return cluster mem reservation average per minute cloudwatch metric
    try:
        response = cwClient.get_metric_statistics( 
            Namespace='AWS/ECS',
            MetricName='MemoryReservation',
            Dimensions=[
                {
                    'Name': 'ClusterName',
                    'Value': clusterName
                },
            ],
            StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=120),
            EndTime=datetime.datetime.utcnow(),
            Period=60,
            Statistics=['Average']
        )
        return response['Datapoints'][0]['Average']

    except Exception:
        logger({'ClusterMemoryError': 'Could not retrieve mem reservation for {}'.format(clusterName)}) 
Example 7
Project: ecscale   Author: omerxx   File: ecscale.py    MIT License 6 votes vote down vote up
def ec2_avg_cpu_utilization(clusterName, asgData, cwclient):
    asg = find_asg(clusterName, asgData)
    response = cwclient.get_metric_statistics( 
        Namespace='AWS/EC2',
        MetricName='CPUUtilization',
        Dimensions=[
            {
                'Name': 'AutoScalingGroupName',
                'Value': asg
            },
        ],
        StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=120),
        EndTime=datetime.datetime.utcnow(),
        Period=60,
        Statistics=['Average']
    )
    return response['Datapoints'][0]['Average'] 
Example 8
Project: pytuber   Author: tefra   File: test_storage.py    MIT License 6 votes vote down vote up
def test_cache(self, time):
        time.side_effect = [10, 20.1, 20.1, 20.5, 20.8]

        def callme(ttl, value, refresh=False):
            return Registry.cache(
                key="foo",
                ttl=timedelta(seconds=ttl),
                func=lambda: value,
                refresh=refresh,
            )

        self.assertEqual("first", callme(10, "first"))
        self.assertEqual(("first", 20.0), Registry.get("foo"))

        self.assertEqual("second", callme(1, "second"))
        self.assertEqual(("second", 21.1), Registry.get("foo"))

        self.assertEqual("second", callme(1, "third"))
        self.assertEqual(("second", 21.1), Registry.get("foo"))

        self.assertEqual("third", callme(100, "third", refresh=True))
        self.assertEqual(("third", 120.8), Registry.get("foo"))

        self.assertEqual(5, time.call_count) 
Example 9
Project: pytuber   Author: tefra   File: services.py    MIT License 6 votes vote down vote up
def get_artist(cls, artist: str) -> Artist:
        """
        Use last.fm api to find an artist by name. The result will be cached
        for 30 days.

        :param str artist: The artist's name to lookup
        :rtype: :class:`pydrag.Artist`
        """
        cls.assert_config()

        cache = Registry.cache(
            key="last.fm_artist_{}".format(artist.lower()),
            ttl=timedelta(days=30),
            func=lambda: Artist.find(artist).to_dict(),
        )
        return Artist(**cache) 
Example 10
Project: pytuber   Author: tefra   File: services.py    MIT License 6 votes vote down vote up
def get_user(cls, username) -> User:
        """
        Use last.fm api to fetch a user by name. The result will be cached for
        24 hours.

        :param str username: The user's name
        :rtype: :class:`pydrag.User`
        """
        cls.assert_config()

        cache = Registry.cache(
            key="last.fm_user_{}".format(username.lower()),
            ttl=timedelta(hours=24),
            func=lambda: User.find(username).to_dict(),
        )
        return User(**cache) 
Example 11
Project: pytuber   Author: tefra   File: cmd_quota.py    MIT License 6 votes vote down vote up
def quota():
    """Show current youtube calculated quota usage."""

    limit = ConfigManager.get(Provider.youtube).data["quota_limit"]
    usage = YouService.get_quota_usage()
    pt_date = YouService.quota_date(obj=True)
    next_reset = timedelta(
        hours=23 - pt_date.hour,
        minutes=59 - pt_date.minute,
        seconds=60 - pt_date.second,
    )

    values = [
        (magenta("Provider:"), Provider.youtube),
        (magenta("Limit:"), limit),
        (magenta("Usage:"), usage),
        (magenta("Next reset:"), str(next_reset)),
    ]

    click.secho(
        tabulate(  # type: ignore
            values, tablefmt="plain", colalign=("right", "left")
        )
    ) 
Example 12
Project: poupool   Author: lostcontrol   File: filtration.py    GNU General Public License v2.0 6 votes vote down vote up
def compute(self):
        remaining_duration = max(timedelta(), self.filtration.delay - self.filtration.duration)
        assert self.period_duration > timedelta()
        remaining_periods = max(1, int(remaining_duration / self.period_duration))
        remaining_time = max(timedelta(), self.reset_hour - datetime.now())
        logger.info("Remaining duration: %s periods: %d time: %s" %
                    (remaining_duration, remaining_periods, remaining_time))
        self.on_duration = min(remaining_time, remaining_duration / remaining_periods)
        if self.on_duration < timedelta(hours=1):
            self.on_duration = timedelta(hours=1)
        self.off_duration = (remaining_time - remaining_duration) / remaining_periods
        if self.off_duration < timedelta():
            self.off_duration = timedelta()
        self.tank_duration = self.tank_percentage * self.on_duration
        if self.tank_duration < timedelta(minutes=1):
            self.tank_duration = timedelta(minutes=1)
        if self.on_duration > self.tank_duration:
            self.on_duration -= self.tank_duration
        logger.info("Duration on: %s tank: %s off: %s" %
                    (self.on_duration, self.tank_duration, self.off_duration)) 
Example 13
Project: parsechain   Author: Suor   File: chains.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def duration(text):
        regexes = [
            r'()(?:(\d\d):)?(\d\d):(\d\d)(?:\s|$)',
            re.compile(r'''\s* (?:(\d+)\s*д[еньяй.]*)?
                           \s* (?:(\d+)\s*ч[ас.]*)?
                           \s* (?:(\d+)\s*м[инуты.]*)?
                           ()''', re.I | re.X)
        ]
        for regex in regexes:
            m = re_find(regex, text)
            if m:
                days, hours, minutes, seconds = [silent(int)(p) or 0 for p in m]
                if days == hours == minutes == 0:
                    return None
                return (days * 24 + hours * 60 + minutes) * 60 + seconds
                # return datetime.timedelta(days=days, hours=hours, minutes=minutes)


# Chain.register('float', _list_first(float))
# @Chain.register
# def func(...):
#     pass


# Advanced introspection 
Example 14
Project: comcast   Author: lachesis   File: pge.py    MIT License 5 votes vote down vote up
def split_days(st, ed):
    assert st < ed
    p = st
    while p < ed:
        n = p + datetime.timedelta(MAX_DAYS)
        if n > ed:
            n = ed
        yield p, n
        p = n 
Example 15
Project: Hasami   Author: Lokraan   File: exchange_processor.py    MIT License 5 votes vote down vote up
def check_exchange_rsi_updates(self, exchange: ccxt.Exchange) -> dict:
		"""
		Checks exchange tickers to see if there has been a significant rsi.
		If there has been it adds it to a dict to be returned.

		Args:
			exchange: exchange to be checked

		Returns:
			a dict of all the updates and their corresponding symbols

		"""
		if not exchange.has['fetchOHLCV']: return {}

		rsi_updates = {}

		await self._aretry.call(exchange.load_markets)

		since = datetime.now() - timedelta(minutes=30*500)
		since = since.timestamp() * 1000

		tasks = [
				self._acalc_rsi(exchange, symbol, since) 
				for symbol in exchange.symbols
			]

		rsi_data = await asyncio.gather(*tasks, return_exceptions=True)

		for data in rsi_data:
			symbol, rsi = data
			if rsi <= self._over_sold or rsi >= self._over_bought:
				if symbol not in self._significant_markets:
					rsi_updates[symbol] = rsi
					self._significant_markets.add(symbol)

			elif rsi in self._significant_markets:
				self._significant_markets.remove(symbol)

		return rsi_updates 
Example 16
Project: mutatest   Author: EvanKepner   File: run.py    MIT License 5 votes vote down vote up
def clean_trial(src_loc: Path, test_cmds: List[str]) -> timedelta:
    """Remove all existing cache files and run the test suite.

    Args:
        src_loc: the directory of the package for cache removal, may be a file
        test_cmds: test running commands for subprocess.run()

    Returns:
        None

    Raises:
        BaselineTestException: if the clean trial does not pass from the test run.
    """
    cache.remove_existing_cache_files(src_loc)

    LOGGER.info("Running clean trial")

    # clean trial will show output all the time for diagnostic purposes
    start = datetime.now()
    clean_run = subprocess.run(test_cmds, capture_output=False)
    end = datetime.now()

    if clean_run.returncode != 0:
        raise BaselineTestException(
            f"Clean trial does not pass, mutant tests will be meaningless.\n"
            f"Output: {str(clean_run.stdout)}"
        )

    return end - start


####################################################################################################
# MUTATION TRIAL RUNNING FUNCTIONS
#################################################################################################### 
Example 17
Project: mutatest   Author: EvanKepner   File: test_cli.py    MIT License 5 votes vote down vote up
def mock_TrialTimes():
    """Mock Trial Time fixture for the CLI."""
    return TrialTimes(
        clean_trial_1=timedelta(days=0, seconds=6, microseconds=0),
        clean_trial_2=timedelta(days=0, seconds=6, microseconds=0),
        mutation_trials=timedelta(days=0, seconds=6, microseconds=0),
    ) 
Example 18
Project: mutatest   Author: EvanKepner   File: conftest.py    MIT License 5 votes vote down vote up
def mock_results_summary(mock_trial_results):
    """Mock results summary from multiple trials."""
    return ResultsSummary(
        results=mock_trial_results,
        n_locs_identified=4,
        n_locs_mutated=4,
        total_runtime=timedelta(days=0, seconds=6, microseconds=0),
    )


####################################################################################################
# FILTERS: MOCK COVERAGE FILE FIXTURES
#################################################################################################### 
Example 19
Project: mutatest   Author: EvanKepner   File: test_run.py    MIT License 5 votes vote down vote up
def test_clean_trial_timedelta(binop_file, monkeypatch):
    """Clean trial results in a timedelta object."""

    def mock_subprocess_run(*args, **kwargs):
        return CompletedProcess(args="pytest", returncode=0)

    monkeypatch.setattr(subprocess, "run", mock_subprocess_run)

    result = run.clean_trial(binop_file.parent, ["pytest"])
    assert isinstance(result, timedelta) 
Example 20
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pretty_time(time, now=datetime.datetime.now()):
    tomorrow = now + datetime.timedelta(days=1)
    next_day = now + datetime.timedelta(days=2)
    next_week = now + datetime.timedelta(weeks=1)
    pretty_fmt = '%-I:%M %p'
    pretty_prefix = ''
    if tomorrow < time < next_day:
        pretty_prefix = 'tomorrow at '
    elif time > next_day and time < next_week:
        pretty_prefix = '%A at '
    elif time > next_week and time.month == now.month and time.year == now.year:
        pretty_prefix = '%A the %-d' + pretty_suffix(time.day) + ' at '
    elif time > next_week and time.year == now.year:
        pretty_prefix = '%B %-d' + pretty_suffix(time.day) + ' at '
    elif time > next_week:
        pretty_prefix = '%B %-d' + pretty_suffix(time.day) + ' %Y at '

    return time.strftime(pretty_prefix + pretty_fmt) 
Example 21
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reblock_timer(duration, cleanup_func):
    if 'TEST_DURATION' in os.environ:
        duration = float(os.environ['TEST_DURATION'])

    def sigint_handler(signal, frame):
        cleanup_func()
        sys.exit(0)
    signals = [signal.SIGINT, signal.SIGHUP]
    for sig in signals:
        signal.signal(sig, sigint_handler)

    end_time = datetime.datetime.now() + datetime.timedelta(minutes=duration)
    ptime = pretty_time(end_time)
    print('allowed until ' + ptime)

    now = time.time()
    end_time = now + (duration * 60)
    while True:
        remaining = end_time - time.time()
        if remaining <= 0:
            break
        if remaining > 1000:
            time.sleep(10)
        else:
            time.sleep(1)

    cleanup_func() 
Example 22
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def minutes_to_morning():
    now = datetime.datetime.now()
    morning = now.replace(hour=6, minute=1, second=0)
    if now.hour > 6:
        morning = morning + datetime.timedelta(days=1)
    return (morning - now).seconds / 60 
Example 23
Project: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 5 votes vote down vote up
def next_occurrences(relative_to=datetime.datetime.today()):
    '''
    Calculate when the rules in RULES will next fire.
    Returns a list of (Rule, datetime.date) tuples.
    '''
    result = []
    for rule in RULES:
        yesterday = relative_to - datetime.timedelta(days=1)
        naive_next = rule.rule.after(yesterday)
        actual_next = rule.relocator(naive_next)
        result.append((rule, actual_next))

    return result 
Example 24
Project: mlbv   Author: kmac   File: mlbgamedata.py    GNU General Public License v3.0 5 votes vote down vote up
def process_game_data(self, game_date, num_days=1):
        game_days_list = list()
        for i in range(0, num_days):
            game_records = self._get_games_by_date(game_date)
            if game_records is not None:
                game_days_list.append((game_date, game_records))
            game_date = datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d") + timedelta(days=1), "%Y-%m-%d")
        return game_days_list 
Example 25
Project: hydrus   Author: HTTP-APIs   File: user.py    MIT License 5 votes vote down vote up
def check_nonce(request: LocalProxy, session: Session) -> bool:
    """check validity of nonce passed by the user."""
    try:
        id_ = request.headers['X-Authentication']
        nonce = session.query(Nonce).filter(Nonce.id == id_).one()
        present = datetime.now()
        present = present - nonce.timestamp
        session.delete(nonce)
        session.commit()
        if present > timedelta(0, 0, 0, 0, 1, 0, 0):
            return False
    except BaseException:
        return False
    return True 
Example 26
Project: pyblish-win   Author: pyblish   File: test_assertions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_AmostEqualWithDelta(self):
        self.assertAlmostEqual(1.1, 1.0, delta=0.5)
        self.assertAlmostEqual(1.0, 1.1, delta=0.5)
        self.assertNotAlmostEqual(1.1, 1.0, delta=0.05)
        self.assertNotAlmostEqual(1.0, 1.1, delta=0.05)

        self.assertAlmostEqual(1.0, 1.0, delta=0.5)
        self.assertRaises(self.failureException, self.assertNotAlmostEqual,
                          1.0, 1.0, delta=0.5)

        self.assertRaises(self.failureException, self.assertAlmostEqual,
                          1.1, 1.0, delta=0.05)
        self.assertRaises(self.failureException, self.assertNotAlmostEqual,
                          1.1, 1.0, delta=0.5)

        self.assertRaises(TypeError, self.assertAlmostEqual,
                          1.1, 1.0, places=2, delta=2)
        self.assertRaises(TypeError, self.assertNotAlmostEqual,
                          1.1, 1.0, places=2, delta=2)

        first = datetime.datetime.now()
        second = first + datetime.timedelta(seconds=10)
        self.assertAlmostEqual(first, second,
                               delta=datetime.timedelta(seconds=20))
        self.assertNotAlmostEqual(first, second,
                                  delta=datetime.timedelta(seconds=5)) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cmp_datetime_DateTime(self):
        now = datetime.datetime.now()
        dt = xmlrpclib.DateTime(now.timetuple())
        self.assertTrue(dt == now)
        self.assertTrue(now == dt)
        then = now + datetime.timedelta(seconds=4)
        self.assertTrue(then >= dt)
        self.assertTrue(dt < then) 
Example 28
Project: backtrader-cn   Author: pandalibin   File: tushare.py    GNU General Public License v3.0 5 votes vote down vote up
def download_delta_data(self):
        """
        Get yesterday's data and append it to collection,
        this method is planned to be executed at each day's 8:30am to update the data.
        1. Connect to arctic and get the library.
        2. Get today's history data from tushare and strip the unused columns.
        3. Store the data to arctic.
        :return: None
        """

        self._init_coll()

        if self._coll_name in self._new_added_colls:
            return

        # 15:00 PM can get today data
        # start = latest_date + 1 day
        latest_date = self.get_data().index[-1]
        start = latest_date + dt.timedelta(days=1)
        start = dt.datetime.strftime(start, '%Y-%m-%d')

        his_data = ts.get_hist_data(
            code=self._coll_name,
            start=start,
            retry_count=5
        )

        # delta data is empty
        if len(his_data) == 0:
            logger.info(
                f'delta data of stock {self._coll_name} is empty, after {start}')
            return

        his_data = bdu.Utils.strip_unused_cols(his_data, *self._unused_cols)

        logger.info(f'got delta data of stock: {self._coll_name}, after {start}')
        self._library.append(self._coll_name, his_data) 
Example 29
Project: backtrader-cn   Author: pandalibin   File: ma.py    GNU General Public License v3.0 5 votes vote down vote up
def next(self):

        if self.order:
            return

        if not self.position:
            if self.sma_s[0] > self.sma_l[0]:
                # Using the current close price to calculate the size to buy, but use
                # the next open price to executed, so it is possible that the order
                # can not be executed due to margin, so set the target to 0.8 instead
                # of 1.0 to reduce the odds of not being executed
                target_long = 0.8
                self.order = self.order_target_percent(target=target_long, valid=bt.Order.DAY)
                if self.datas[0].datetime.date() == dt.datetime.now().date() - dt.timedelta(days=1):
                    stock_id = self.params.ma_periods.get('stock_id')
                    action = 'buy'
                    bsu.Utils.log(
                        self.datas[0].datetime.date(),
                        f'Market Signal: stock {stock_id}, action: {action}, '
                        f'adjust position to {target_long:.2f}')
                    symbol = dt.datetime.now().strftime('%Y-%m-%d')
                    bsu.Utils.write_daily_alert(symbol, stock_id, action)
        else:
            if self.sma_s[0] <= self.sma_l[0]:
                target_short = 0.0
                self.order = self.order_target_percent(target=target_short, valid=bt.Order.DAY)
                if self.datas[0].datetime.date() == dt.datetime.now().date() - dt.timedelta(days=1):
                    stock_id = self.params.ma_periods.get('stock_id')
                    action = 'sell'
                    bsu.Utils.log(
                        self.datas[0].datetime.date(),
                        f'Market Signal: stock {stock_id}, action: {action}, '
                        f'adjust position to {target_short:.2f}')
                    symbol = dt.datetime.now().strftime('%Y-%m-%d')
                    bsu.Utils.write_daily_alert(symbol, stock_id, action) 
Example 30
Project: backtrader-cn   Author: pandalibin   File: stock_match.py    GNU General Public License v3.0 5 votes vote down vote up
def update_sina_stock_match():
    date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    msg = get_market_signal_by_date(date)
    user = StockMatch(
        username=conf.SINA_CONFIG['username'],
        password=conf.SINA_CONFIG['password'],
    )
    for stock_code in msg['buy']:
        user.buy(stock_code)
        # 经过测试,每隔3S进行一次买入操作的频率最合适
        time.sleep(3)
    else:
        logger.info("没有股票需要买入") 
Example 31
Project: backtrader-cn   Author: pandalibin   File: test_datas_tushare.py    GNU General Public License v3.0 5 votes vote down vote up
def _test_download_delta_data(self, mock_get_hist_data):
        coll_name = '000651'
        ts_his_data = bdt.TsHisData(coll_name)

        yesterday = dt.datetime.now() - dt.timedelta(days=1)
        mock_delta_data = pd.DataFrame(data={
            'open': 38,
            'high': 39,
            'close': 40,
            'low': 41,
            'volume': 42,
            'price_change': 43,
            'p_change': 44,
            'ma5': 45,
            'ma10': 46,
            'ma20': 47,
            'v_ma5': 48,
            'v_ma10': 49,
            'v_ma20': 50,
            'turnover': 51
        }, index=[dt.datetime.strftime(yesterday, '%Y-%m-%d')])

        mock_get_hist_data.return_value = mock_delta_data

        ts_his_data.download_delta_data()

        hist_data_000651 = ts_his_data.get_data()

        self.assertEqual(len(hist_data_000651), 3)
        self.assertEqual(dt.datetime.strftime(hist_data_000651.index[-1], '%Y-%m-%d'),
                         dt.datetime.strftime(yesterday, '%Y-%m-%d'))
        lib = models.get_library(conf.CN_STOCK_LIBNAME)
        lib.delete(coll_name) 
Example 32
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    Apache License 2.0 5 votes vote down vote up
def test_build_data_select_latest(self, blank_state):
        """Test that build data can be selected for only latest instance."""
        build_data_latest = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data_old = copy.deepcopy(build_data_latest)
        build_data_old['collected_date'] = build_data_latest[
            'collected_date'] - timedelta(days=1)
        build_data_old['task_id'] = uuid.uuid4()

        build_data1 = objects.BuildData(**build_data_latest)
        build_data2 = objects.BuildData(**build_data_old)

        result = blank_state.post_build_data(build_data1)

        assert result

        result = blank_state.post_build_data(build_data2)

        assert result

        bd_list = blank_state.get_build_data(node_name='foo', latest=True)

        assert len(bd_list) == 1

        assert bd_list[0].to_dict() == build_data1.to_dict() 
Example 33
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: app.py    Apache License 2.0 5 votes vote down vote up
def _make_timedelta(value):
    if not isinstance(value, timedelta):
        return timedelta(seconds=value)
    return value 
Example 34
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: app.py    Apache License 2.0 5 votes vote down vote up
def _make_timedelta(value):
    if not isinstance(value, timedelta):
        return timedelta(seconds=value)
    return value 
Example 35
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 5 votes vote down vote up
def _get_retry_after(self):
        value = self.headers.get('retry-after')
        if value is None:
            return
        elif value.isdigit():
            return datetime.utcnow() + timedelta(seconds=int(value))
        return parse_date(value) 
Example 36
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def parse_date(value):
    """Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    """
    if value:
        t = parsedate_tz(value.strip())
        if t is not None:
            try:
                year = t[0]
                # unfortunately that function does not tell us if two digit
                # years were part of the string, or if they were prefixed
                # with two zeroes.  So what we do is to assume that 69-99
                # refer to 1900, and everything below to 2000
                if year >= 0 and year <= 68:
                    year += 2000
                elif year >= 69 and year <= 99:
                    year += 1900
                return datetime(*((year,) + t[1:7])) - \
                       timedelta(seconds=t[-1] or 0)
            except (ValueError, OverflowError):
                return None 
Example 37
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 5 votes vote down vote up
def _get_retry_after(self):
        value = self.headers.get('retry-after')
        if value is None:
            return
        elif value.isdigit():
            return datetime.utcnow() + timedelta(seconds=int(value))
        return parse_date(value) 
Example 38
Project: durationpy   Author: icholy   File: duration.py    MIT License 5 votes vote down vote up
def from_str(duration):
    """Parse a duration string to a datetime.timedelta"""

    if duration in ("0", "+0", "-0"):
        return datetime.timedelta()

    pattern = re.compile('([\d\.]+)([a-zµμ]+)')
    total = 0
    sign = -1 if duration[0] == '-' else 1
    matches = pattern.findall(duration)

    if not len(matches):
        raise Exception("Invalid duration {}".format(duration))

    for (value, unit) in matches:
        if unit not in units:
            raise Exception(
                "Unknown unit {} in duration {}".format(unit, duration))
        try:
            total += float(value) * units[unit]
        except:
            raise Exception(
                "Invalid value {} in duration {}".format(value, duration))

    microseconds = total / _microsecond_size
    return datetime.timedelta(microseconds=sign * microseconds) 
Example 39
Project: durationpy   Author: icholy   File: duration.py    MIT License 5 votes vote down vote up
def to_str(delta, extended=False):
    """Format a datetime.timedelta to a duration string"""

    total_seconds = delta.total_seconds()
    sign = "-" if total_seconds < 0 else ""
    nanoseconds = abs(total_seconds * _second_size)

    if total_seconds < 1:
        result_str = _to_str_small(nanoseconds, extended)
    else:
        result_str = _to_str_large(nanoseconds, extended)

    return "{}{}".format(sign, result_str) 
Example 40
Project: everyclass-server   Author: everyclass   File: ics_generator.py    Mozilla Public License 2.0 5 votes vote down vote up
def _get_datetime(week: int, day: int, time: Tuple[int, int], semester: Tuple[int, int, int]) -> datetime:
    """
    根据学期、周次、时间,生成 `datetime` 类型的时间

    :param week: 周次
    :param day: 星期
    :param time: 时间tuple(时,分)
    :param semester: 学期
    :return: datetime 类型的时间
    """
    config = get_config()
    tz = pytz.timezone("Asia/Shanghai")
    dt = datetime(*(config.AVAILABLE_SEMESTERS[semester]['start'] + time), tzinfo=tz)  # noqa: T484
    dt += timedelta(days=(week - 1) * 7 + day)  # 调整到当前周

    if 'adjustments' in config.AVAILABLE_SEMESTERS[semester]:
        ymd = (dt.year, dt.month, dt.day)
        adjustments = config.AVAILABLE_SEMESTERS[semester]['adjustments']
        if ymd in adjustments:
            if adjustments[ymd]['to']:
                # 调课
                dt = dt.replace(year=adjustments[ymd]['to'][0],
                                month=adjustments[ymd]['to'][1],
                                day=adjustments[ymd]['to'][2])
            else:
                # 冲掉的课年份设置为1984,返回之后被抹去
                dt = dt.replace(year=1984)

    return dt 
Example 41
Project: shelter   Author: seznam   File: test_utils_imports.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_import_object():
    assert dt.timedelta == import_object('datetime.timedelta') 
Example 42
Project: getRainfallData   Author: craigdsouza   File: getpastRainfallData.py    GNU General Public License v3.0 5 votes vote down vote up
def date_range(dateStart,dateEnd):
    dtIndex = (dateEnd + timedelta(days=1) - dateStart).days #Counts difference between start and end dates
    dates = []
    for i in range(dtIndex):
        if i % 7 == 0:
            dates.append(dateStart + timedelta(days=i))
    return dates 
Example 43
Project: pytuber   Author: tefra   File: test_services.py    MIT License 5 votes vote down vote up
def test_get_tags(self, get_top_tags, time, assert_config):
        time.return_value = 1

        get_top_tags.side_effect = [
            [Tag(name=i) for i in range(0, 250)],
            [Tag(name=i) for i in range(250, 500)],
            [Tag(name=i) for i in range(500, 750)],
            [Tag(name=i) for i in range(750, 1000)],
        ]

        names = [t.name for t in LastService.get_tags()]
        self.assertEqual(list(range(0, 1000)), names)

        get_top_tags.assert_has_calls(
            [
                mock.call(limit=250, page=1),
                mock.call(limit=250, page=2),
                mock.call(limit=250, page=3),
                mock.call(limit=250, page=4),
            ]
        )

        tags, ttl = Registry.get("last.fm_tag_list")
        self.assertEqual(1000, len(tags))
        self.assertEqual({"name": 0}, tags[0])
        self.assertEqual(timedelta(days=30, seconds=1).total_seconds(), ttl)
        assert_config.assert_called_once() 
Example 44
Project: pytuber   Author: tefra   File: test_services.py    MIT License 5 votes vote down vote up
def test_get_artist(self, find, time, assert_config):
        time.return_value = 1

        find.return_value = Artist(name="Queen")

        artist = LastService.get_artist("quueee")
        self.assertEqual(Artist(name="Queen"), artist)

        find.assert_called_once_with("quueee")

        artist, ttl = Registry.get("last.fm_artist_quueee")
        self.assertEqual({"name": "Queen"}, artist)

        self.assertEqual(timedelta(days=30, seconds=1).total_seconds(), ttl)
        assert_config.assert_called_once() 
Example 45
Project: pytuber   Author: tefra   File: test_services.py    MIT License 5 votes vote down vote up
def test_get_user(self, find, time, assert_config):
        time.return_value = 1
        my_user = self.get_user()
        find.return_value = my_user

        self.assertEqual(my_user, LastService.get_user("rj"))

        find.assert_called_once_with("rj")

        user, ttl = Registry.get("last.fm_user_rj")
        self.assertEqual(self.get_user().to_dict(), user)

        self.assertEqual(timedelta(hours=24, seconds=1).total_seconds(), ttl)
        assert_config.assert_called_once() 
Example 46
Project: pytuber   Author: tefra   File: test_services.py    MIT License 5 votes vote down vote up
def test_quota_date(self):
        expected = (datetime.utcnow() - timedelta(hours=8)).strftime("%Y%m%d")
        self.assertEqual(expected, YouService.quota_date()) 
Example 47
Project: pytuber   Author: tefra   File: storage.py    MIT License 5 votes vote down vote up
def cache(
        cls, key: str, func: Callable, ttl: timedelta, refresh: bool = False
    ):
        registry = cls()
        if refresh or key not in registry or registry[key][1] < time.time():
            registry[key] = (func(), time.time() + ttl.total_seconds())
        return registry[key][0] 
Example 48
Project: pytuber   Author: tefra   File: services.py    MIT License 5 votes vote down vote up
def quota_date(cls, obj: bool = False):
        """
        Youtube daily quotas reset at midnight Pacific Time (PT). Return the
        current quota date string.

        :return: str
        """
        dt = datetime.utcnow() - timedelta(hours=8)
        return dt if obj else dt.strftime("%Y%m%d") 
Example 49
Project: poupool   Author: lostcontrol   File: filtration.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, encoder):
        self.__encoder = encoder
        self.filtration = Timer("filtration")
        self.current = Timer("current")
        self.reset_hour = 0
        self.__period = 3
        self.tank_percentage = 0.1
        self.daily = timedelta(hours=10)
        self.period_duration = timedelta(hours=1)
        self.off_duration = timedelta()
        self.on_duration = timedelta()
        self.tank_duration = timedelta()
        self.__duration_last_save = datetime.now() 
Example 50
Project: poupool   Author: lostcontrol   File: filtration.py    GNU General Public License v2.0 5 votes vote down vote up
def reset_hour(self, hour):
        tm = datetime.now()
        self.__next_reset = tm.replace(hour=hour, minute=0, second=0, microsecond=0)
        if self.__next_reset < tm:
            self.__next_reset += timedelta(days=1)