How to use the datetime.date function in DateTime

To help you get started, we’ve selected a few DateTime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github all-of-us / raw-data-repository / tests / dao_tests / test_ehr_dao.py View on Github external
def test_get_active_organization_counts_in_interval_quarter(self):
        self._fill_calendar_range(datetime.date(2018, 12, 1), datetime.date(2020, 1, 1))

        self._save_ehr_receipt(org=self.org_foo_a, receipt_time=datetime.datetime(2019, 5, 1))
        self._save_ehr_receipt(org=self.org_bar_a, receipt_time=datetime.datetime(2019, 5, 1))
        self._save_ehr_receipt(org=self.org_foo_a, receipt_time=datetime.datetime(2019, 11, 1))

        results = self.ehr_receipt_dao.get_active_organization_counts_in_interval(
            start_date=datetime.datetime(2019, 1, 1), end_date=datetime.datetime(2020, 1, 1), interval=INTERVAL_QUARTER
        )

        self.assertEqual(
            [(r["start_date"], r["active_organization_count"]) for r in results],
            [
                (datetime.date(2019, 1, 1), 0),
                (datetime.date(2019, 4, 1), 2),
                (datetime.date(2019, 7, 1), 0),
                (datetime.date(2019, 10, 1), 1),
                (datetime.date(2020, 1, 1), 0),
            ],
github CroceRossaItaliana / jorvik / formazione / models.py View on Github external
def nuovo(cls, anno=None, **kwargs):
        """
        Metodo per creare un nuovo corso. Crea progressivo automaticamente.
        :param anno: Anno di creazione del corso.
        :param kwargs: Parametri per la creazione del corso.
        :return:
        """

        anno = anno or datetime.date.today().year
        try:  # Per il progressivo, cerca ultimo corso
            ultimo = cls.objects.filter(anno=anno).latest('progressivo')
            progressivo = ultimo.progressivo + 1
        except:
            progressivo = 1  # Se non esiste, inizia da 1

        c = CorsoBase(anno=anno, progressivo=progressivo, **kwargs)
        c.min_participants, c.max_participants = c.titolo_cri.numero_partecipazioni
        c.save()
        return c
github KarypidisParis / crawler_for_investing.com / Articles.py View on Github external
article_titles = tree.xpath(self.indicatorData['xpath_articles'] + self.indicatorData['xpath_articles_title'])
		article_title_links = tree.xpath(self.indicatorData['xpath_articles'] + self.indicatorData['xpath_articles_link'])
		article_dates =  tree.xpath(self.indicatorData['xpath_articles'] + self.indicatorData['xpath_articles_date'])

		try:
			article_titles.remove(" ")
		except ValueError:
			pass
				
		#if ~40 articles are outdated stop the procedure
		for i in range(len(article_titles)):
			#check if 'date' is formet like "Dec 22, 2017" or "11 hours before" or "am" etc
			#if it is set today for date 
			if "hour" in article_dates[i] or "minute" in article_dates[i] or "second" in article_dates[i] or "am" in article_dates[i] or "pm" in article_dates[i]:
				article_dates[i] = datetime.date.today()
				article_date = article_dates[i]
			else:
				if self.indicatorData['name_API'] == 'reuters':
					#find differencies in dates #just a comma
					article_date = datetime.datetime.strptime(article_dates[i].replace('\xa0-\xa0',''), "%b %d %Y").date()					
				elif self.indicatorData['name_API'] == 'investing':	
					article_date = datetime.datetime.strptime(article_dates[i].replace('\xa0-\xa0',''), "%b %d, %Y").date()
#			print(article_date)	

			#check if article date is in desired date period
			if self.parameters['st_date'] <= article_date and article_date <= self.parameters['end_date']:
				article_title = article_titles[i].replace("\n","").replace("\t","")
				if self.filterArticle(article_title):
					self.articles[self.article_counter] = {'article_title' : article_title, 'article_title_link' : article_title_links[i], 'article_date' : article_date}
					self.article_counter += 1
			else:
github athul / PP-Suku / generator / migrations / 0001_initial.py View on Github external
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='user',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('Name', models.CharField(default='', max_length=100)),
                ('Bio', models.TextField(blank=True, default='')),
                ('College', models.CharField(default='', max_length=100)),
                ('dob', models.DateField(default=datetime.date(2019, 9, 10))),
                ('Phone', models.BigIntegerField(blank=True)),
                ('Email', models.EmailField(default='', max_length=254)),
                ('Designations', models.CharField(default='', max_length=150)),
                ('Skill1', models.CharField(default='', max_length=100)),
                ('Skill2', models.CharField(default='', max_length=100)),
                ('Skill3', models.CharField(blank=True, default='', max_length=100)),
                ('Skill4', models.CharField(blank=True, default='', max_length=100)),
                ('GitHub', models.CharField(blank=True, default='', max_length=150)),
                ('Twitter', models.CharField(blank=True, default='', max_length=150)),
                ('LinkedIn', models.CharField(blank=True, default='', max_length=150)),
                ('Instagram', models.CharField(blank=True, default='', max_length=150)),
                ('Project1', models.CharField(default='', max_length=50)),
                ('Project1desc', models.CharField(default='', max_length=150)),
                ('Projecturl1', models.URLField(default='', max_length=150)),
                ('Project2', models.CharField(default='', max_length=50)),
                ('Project2desc', models.CharField(default='', max_length=150)),
github quantmind / lux / extensions / forms / fields.py View on Github external
def _clean(self, value, instance):
        if not isinstance(value, date):
            try:
                value = dateparser(value)
            except Exception:
                raise ValidationError(
                    self.validation_error.format(value))
        return self.todate(value)
github La0 / coach / sport / stats.py View on Github external
def end(self):
    # End Date
    _, last_day = monthrange(self.year, self.month)
    return  date(self.year, self.month, last_day)
github Pegase745 / sqlalchemy-datatables / examples / pyramid_tut / pyramid_tut / __init__.py View on Github external
config.add_route('data_advanced', '/data_advanced')
    config.add_route('data_yadcf', '/data_yadcf')
    config.add_route('dt_110x', '/dt_110x')
    config.add_route('dt_110x_func', '/dt_110x_func')
    config.add_route('dt_110x_custom_column', '/dt_110x_custom_column')
    config.add_route('dt_110x_basic_column_search',
                     '/dt_110x_basic_column_search')
    config.add_route('dt_110x_advanced_column_search',
                     '/dt_110x_advanced_column_search')
    config.add_route('dt_110x_yadcf',
                     '/dt_110x_yadcf')
    config.scan()

    # only for advanced example
    json_renderer = JSON()
    json_renderer.add_adapter(date, date_adapter)
    config.add_renderer('json_with_dates', json_renderer)

    return config.make_wsgi_app()
github Shayen / sal_pipeline / src / log.py View on Github external
def __init__(self, name = "GLobal" ):

		self.name = name
		self.logger = logging.getLogger(__main__.__name__)
		self._clearHandlers()
		self.logger.setLevel(logging.INFO)

		logFileName = str (datetime.date.today() )

		# create a file handler
		loggerPath = '{logDir}/{tool}/{user}/{logFileName}.log'.format(logDir = env.log_dirPath(), tool=name,user=env.user, logFileName = logFileName)
		self._checkLogFolder(name, env.user)
		handler = logging.FileHandler( loggerPath )
		handler.setLevel(logging.INFO)

		print loggerPath

		# create a logging format
		formatter = logging.Formatter('%(asctime)s - %(lineno)d - %(name)s - %(levelname)s - %(message)s')
		handler.setFormatter(formatter)

		# add the handlers to the self.logger
		self.logger.addHandler(handler)
github OpenSatKit / OpenSatKit / cfs / tools / gen_app_code / app_code_configs.py View on Github external
parse_input_file(itm)
                break
            elif curOpt == "MISSION":
                g_Mission = itm
            elif curOpt == "OWNER":
                g_Owner = itm
            elif curOpt == "OUTDIR":
                g_OutDir = itm
            elif curOpt == "TBLS":
                g_Tbls.append(itm)
            elif curOpt == "APPS":
                g_Apps.append(itm)
            else:
                pass

    g_Date = datetime.date.today()
github silverapp / silver / silver / models / subscriptions.py View on Github external
def _get_proration_status_and_percent(self, start_date, end_date):
        """
        Returns the proration percent (how much of the interval will be billed)
        and the status (if the subscription is prorated or not).

        :returns: a tuple containing (Decimal(percent), status) where status
            can be one of [True, False]. The decimal value will from the
            interval [0.00; 1.00].
        :rtype: tuple
        """

        first_day_of_month = date(start_date.year, start_date.month, 1)
        last_day_index = calendar.monthrange(start_date.year,
                                             start_date.month)[1]
        last_day_of_month = date(start_date.year, start_date.month,
                                 last_day_index)

        if start_date == first_day_of_month and end_date == last_day_of_month:
            return False, Decimal('1.0000')
        else:
            days_in_full_interval = (last_day_of_month - first_day_of_month).days + 1
            days_in_interval = (end_date - start_date).days + 1
            percent = 1.0 * days_in_interval / days_in_full_interval
            percent = Decimal(percent).quantize(Decimal('0.0000'))

            return True, percent