Python datetime.datetime.combine() Examples

The following are 30 code examples of datetime.datetime.combine(). 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 datetime.datetime , or try the search function .
Example #1
Source File: test.py    From casepro with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def assertExcelRow(self, sheet, row_num, values, tz=None):
        """
        Asserts the cell values in the given worksheet row. Date values are converted using the provided timezone.
        """
        expected_values = []
        for expected in values:
            # if expected value is datetime, localize and remove microseconds
            if isinstance(expected, datetime):
                expected = expected.astimezone(tz).replace(microsecond=0, tzinfo=None)
            elif isinstance(expected, date):
                expected = datetime.combine(expected, time(0, 0))

            expected_values.append(expected)

        actual_values = []
        for c in range(0, sheet.ncols):
            cell = sheet.cell(row_num, c)
            actual = cell.value

            if cell.ctype == XL_CELL_DATE:
                actual = datetime(*xldate_as_tuple(actual, sheet.book.datemode))

            actual_values.append(actual)

        self.assertEqual(actual_values, expected_values) 
Example #2
Source File: test_datetime.py    From BinderFilter with MIT License 7 votes vote down vote up
def test_combine(self):
        d = date(2002, 3, 4)
        t = time(18, 45, 3, 1234)
        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        combine = self.theclass.combine
        dt = combine(d, t)
        self.assertEqual(dt, expected)

        dt = combine(time=t, date=d)
        self.assertEqual(dt, expected)

        self.assertEqual(d, dt.date())
        self.assertEqual(t, dt.time())
        self.assertEqual(dt, combine(dt.date(), dt.time()))

        self.assertRaises(TypeError, combine) # need an arg
        self.assertRaises(TypeError, combine, d) # need two args
        self.assertRaises(TypeError, combine, t, d) # args reversed
        self.assertRaises(TypeError, combine, d, t, 1) # too many args
        self.assertRaises(TypeError, combine, "date", "time") # wrong types 
Example #3
Source File: test_timestamp.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_class_ops_pytz(self):
        def compare(x, y):
            assert (int(Timestamp(x).value / 1e9) ==
                    int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #4
Source File: fact_billing_dao.py    From notifications-api with MIT License 6 votes vote down vote up
def fetch_billing_data_for_day(process_day, service_id=None, check_permissions=False):
    start_date = convert_bst_to_utc(datetime.combine(process_day, time.min))
    end_date = convert_bst_to_utc(datetime.combine(process_day + timedelta(days=1), time.min))
    current_app.logger.info("Populate ft_billing for {} to {}".format(start_date, end_date))
    transit_data = []
    if not service_id:
        services = Service.query.all()
    else:
        services = [Service.query.get(service_id)]

    for service in services:
        for notification_type in (SMS_TYPE, EMAIL_TYPE, LETTER_TYPE):
            if (not check_permissions) or service.has_permission(notification_type):
                table = get_notification_table_to_use(service, notification_type, process_day,
                                                      has_delete_task_run=False)
                results = _query_for_billing_data(
                    table=table,
                    notification_type=notification_type,
                    start_date=start_date,
                    end_date=end_date,
                    service=service
                )
                transit_data += results

    return transit_data 
Example #5
Source File: test_timestamp.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_class_ops_dateutil(self):
        def compare(x, y):
            assert (int(np.round(Timestamp(x).value / 1e9)) ==
                    int(np.round(Timestamp(y).value / 1e9)))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(tzutc()))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #6
Source File: test_timestamp.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_class_ops_pytz(self):
        def compare(x, y):
            assert (int(Timestamp(x).value / 1e9) ==
                    int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #7
Source File: fact_notification_status_dao.py    From notifications-api with MIT License 6 votes vote down vote up
def fetch_notification_status_for_day(process_day, notification_type):
    start_date = convert_bst_to_utc(datetime.combine(process_day, time.min))
    end_date = convert_bst_to_utc(datetime.combine(process_day + timedelta(days=1), time.min))

    current_app.logger.info("Fetch ft_notification_status for {} to {}".format(start_date, end_date))

    all_data_for_process_day = []
    services = Service.query.all()
    # for each service query notifications or notification_history for the day, depending on their data retention
    for service in services:
        table = get_notification_table_to_use(service, notification_type, process_day, has_delete_task_run=False)

        data_for_service_and_type = query_for_fact_status_data(
            table=table,
            start_date=start_date,
            end_date=end_date,
            notification_type=notification_type,
            service_id=service.id
        )

        all_data_for_process_day += data_for_service_and_type

    return all_data_for_process_day 
Example #8
Source File: date.py    From mimesis with MIT License 6 votes vote down vote up
def datetime(self, start: int = 2000, end: int = CURRENT_YEAR,
                 timezone: Optional[str] = None) -> DateTime:
        """Generate random datetime.

        :param start: Minimum value of year.
        :param end: Maximum value of year.
        :param timezone: Set custom timezone (pytz required).
        :return: Datetime
        """
        datetime_obj = datetime.combine(
            date=self.date(start, end),
            time=self.time(),
        )
        if timezone:
            if not pytz:
                raise ImportError('Timezones are supported only with pytz')
            tz = pytz.timezone(timezone)
            datetime_obj = tz.localize(datetime_obj)

        return datetime_obj 
Example #9
Source File: test_datetime.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_combine(self):
        d = date(2002, 3, 4)
        t = time(18, 45, 3, 1234)
        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        combine = self.theclass.combine
        dt = combine(d, t)
        self.assertEqual(dt, expected)

        dt = combine(time=t, date=d)
        self.assertEqual(dt, expected)

        self.assertEqual(d, dt.date())
        self.assertEqual(t, dt.time())
        self.assertEqual(dt, combine(dt.date(), dt.time()))

        self.assertRaises(TypeError, combine) # need an arg
        self.assertRaises(TypeError, combine, d) # need two args
        self.assertRaises(TypeError, combine, t, d) # args reversed
        self.assertRaises(TypeError, combine, d, t, 1) # too many args
        self.assertRaises(TypeError, combine, "date", "time") # wrong types 
Example #10
Source File: column.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def convert_string_to_datetime(value):
    """Convert a given value to datetime

    :param value:
    :return: datetime value
    """
    if value is None:
        return None
    elif isinstance(value, datetime):
        return value
    elif isinstance(value, date):
        return datetime.combine(value, datetime.min.time())
    elif isinstance(value, str):
        return parse(value)

    return value 
Example #11
Source File: test_schedule.py    From restatic with GNU General Public License v3.0 6 votes vote down vote up
def test_schedule_tab(app, qtbot):
    main = app.main_window
    tab = main.scheduleTab
    qtbot.mouseClick(tab.scheduleApplyButton, QtCore.Qt.LeftButton)
    assert tab.nextBackupDateTimeLabel.text() == "None scheduled"

    tab.scheduleIntervalRadio.setChecked(True)
    tab.scheduleIntervalHours.setValue(5)
    tab.scheduleIntervalMinutes.setValue(10)
    qtbot.mouseClick(tab.scheduleApplyButton, QtCore.Qt.LeftButton)
    assert tab.nextBackupDateTimeLabel.text().startswith("20")

    tab.scheduleOffRadio.setChecked(True)
    qtbot.mouseClick(tab.scheduleApplyButton, QtCore.Qt.LeftButton)
    assert tab.nextBackupDateTimeLabel.text() == "None scheduled"

    tab.scheduleFixedRadio.setChecked(True)
    tab.scheduleFixedTime.setTime(QtCore.QTime(23, 59))
    qtbot.mouseClick(tab.scheduleApplyButton, QtCore.Qt.LeftButton)
    next_backup = dt.combine(date.today(), time(23, 59))
    assert tab.nextBackupDateTimeLabel.text() == next_backup.strftime("%Y-%m-%d %H:%M") 
Example #12
Source File: test_timestamp.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_class_ops_dateutil(self):
        def compare(x, y):
            assert (int(np.round(Timestamp(x).value / 1e9)) ==
                    int(np.round(Timestamp(y).value / 1e9)))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(tzutc()))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #13
Source File: test_datetime.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_combine(self):
        d = date(2002, 3, 4)
        t = time(18, 45, 3, 1234)
        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        combine = self.theclass.combine
        dt = combine(d, t)
        self.assertEqual(dt, expected)

        dt = combine(time=t, date=d)
        self.assertEqual(dt, expected)

        self.assertEqual(d, dt.date())
        self.assertEqual(t, dt.time())
        self.assertEqual(dt, combine(dt.date(), dt.time()))

        self.assertRaises(TypeError, combine) # need an arg
        self.assertRaises(TypeError, combine, d) # need two args
        self.assertRaises(TypeError, combine, t, d) # args reversed
        self.assertRaises(TypeError, combine, d, t, 1) # too many args
        self.assertRaises(TypeError, combine, "date", "time") # wrong types 
Example #14
Source File: api.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_partition(self, partition_date: date):
        """Create a daily partition for the metric.api_history table."""
        start_ts = datetime.combine(partition_date, time.min)
        end_ts = datetime.combine(partition_date, time.max)
        db_request = self._build_db_request(
            sql_file_name='create_api_metric_partition.sql',
            args=dict(start_ts=str(start_ts), end_ts=str(end_ts)),
            sql_vars=dict(partition=partition_date.strftime('%Y%m%d'))
        )
        self.cursor.execute(db_request)

        db_request = self._build_db_request(
            sql_file_name='create_api_metric_partition_index.sql',
            sql_vars=dict(partition=partition_date.strftime('%Y%m%d'))
        )
        self.cursor.execute(db_request) 
Example #15
Source File: uci_single_households.py    From dts with MIT License 6 votes vote down vote up
def process_csv():
    """
    Parse the datetime field, Sort the values accordingly and save the new dataframe to disk
    """
    df = pd.read_csv(os.path.join(config['data'],'UCI_household_power_consumption.csv'), sep=';')
    df[DATETIME] = list(map(lambda d: datetime.combine(datetime.strptime(d[0], '%d/%m/%Y').date(),
                                                           datetime.strptime(d[1], '%H:%M:%S').time()),
                              df[['Date', 'Time']].values))
    df = df.sort_values([DATETIME]).reset_index(drop=True)
    df = df[[DATETIME, TARGET]]
    df[DATETIME] = pd.to_datetime(df[DATETIME], utc=False)
    def parse(x):
        try:
            return np.float64(x)
        except:
            return np.nan
    df[TARGET] = df[TARGET].apply(lambda x: parse(x))
    df.to_csv(os.path.join(config['data'], 'UCI_household_power_consumption_synth.csv'), index=False) 
Example #16
Source File: datetimetester.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_combine(self):
        d = date(2002, 3, 4)
        t = time(18, 45, 3, 1234)
        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        combine = self.theclass.combine
        dt = combine(d, t)
        self.assertEqual(dt, expected)

        dt = combine(time=t, date=d)
        self.assertEqual(dt, expected)

        self.assertEqual(d, dt.date())
        self.assertEqual(t, dt.time())
        self.assertEqual(dt, combine(dt.date(), dt.time()))

        self.assertRaises(TypeError, combine) # need an arg
        self.assertRaises(TypeError, combine, d) # need two args
        self.assertRaises(TypeError, combine, t, d) # args reversed
        self.assertRaises(TypeError, combine, d, t, 1) # too many args
        self.assertRaises(TypeError, combine, "date", "time") # wrong types
        self.assertRaises(TypeError, combine, d, "time") # wrong type
        self.assertRaises(TypeError, combine, "date", t) # wrong type 
Example #17
Source File: test_timestamp.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_class_ops_dateutil(self):
        def compare(x, y):
            assert (int(np.round(Timestamp(x).value / 1e9)) ==
                    int(np.round(Timestamp(y).value / 1e9)))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(tzutc()))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #18
Source File: test_timestamp.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_class_ops_pytz(self):
        def compare(x, y):
            assert (int(Timestamp(x).value / 1e9) ==
                    int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example #19
Source File: utils.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def today(tzinfo=None):
    """
    Returns a :py:class:`datetime` representing the current day at midnight

    :param tzinfo:
        The time zone to attach (also used to determine the current day).

    :return:
        A :py:class:`datetime.datetime` object representing the current day
        at midnight.
    """

    dt = datetime.now(tzinfo)
    return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) 
Example #20
Source File: graphs.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def get_datestamp(d):
        """Return the Flot datestamp for a datetime.date object"""
        return timegm(datetime.combine(d, time()).timetuple()) * 1000 
Example #21
Source File: mysched.py    From Pipulate with MIT License 5 votes vote down vote up
def minute_adder(minutes):
    the_time = datetime.now().time()
    today = date.today()
    beat = timedelta(minutes=minutes)
    return_value = datetime.combine(today, the_time) + beat
    return return_value 
Example #22
Source File: mutations.py    From pycon with MIT License 5 votes vote down vote up
def add_minutes_to_time(time: time, minutes: int) -> time:
    return (datetime.combine(date(1, 1, 1), time) + timedelta(minutes=minutes)).time() 
Example #23
Source File: offsets.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def apply(self, other):
        if isinstance(other, datetime):
            n = self.n
            wday = other.weekday()

            # avoid slowness below by operating on weeks first
            weeks = n // 5
            if n <= 0 and wday > 4:
                # roll forward
                n += 1

            n -= 5 * weeks

            # n is always >= 0 at this point
            if n == 0 and wday > 4:
                # roll back
                days = 4 - wday
            elif wday > 4:
                # roll forward
                days = (7 - wday) + (n - 1)
            elif wday + n <= 4:
                # shift by n days without leaving the current week
                days = n
            else:
                # shift by n days plus 2 to get past the weekend
                days = n + 2

            result = other + timedelta(days=7 * weeks + days)
            if self.offset:
                result = result + self.offset
            return result

        elif isinstance(other, (timedelta, Tick)):
            return BDay(self.n, offset=self.offset + other,
                        normalize=self.normalize)
        else:
            raise ApplyTypeError('Only know how to combine business day with '
                                 'datetime or timedelta.') 
Example #24
Source File: utils.py    From pipenv with MIT License 5 votes vote down vote up
def today(tzinfo=None):
    """
    Returns a :py:class:`datetime` representing the current day at midnight

    :param tzinfo:
        The time zone to attach (also used to determine the current day).

    :return:
        A :py:class:`datetime.datetime` object representing the current day
        at midnight.
    """

    dt = datetime.now(tzinfo)
    return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) 
Example #25
Source File: helpers.py    From okcupyd with MIT License 5 votes vote down vote up
def date_from_weekday(weekday):
    today = datetime.now()
    incoming_weekday_ordinal = weekday_to_ordinal[weekday.lower()]
    today_ordinal = today.weekday()
    difference = (today_ordinal - incoming_weekday_ordinal
                  if today_ordinal > incoming_weekday_ordinal else
                  7 - incoming_weekday_ordinal + today_ordinal)
    return datetime.combine(today - timedelta(days=difference),
                            datetime.min.time()) 
Example #26
Source File: utils.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def today(tzinfo=None):
    """
    Returns a :py:class:`datetime` representing the current day at midnight

    :param tzinfo:
        The time zone to attach (also used to determine the current day).

    :return:
        A :py:class:`datetime.datetime` object representing the current day
        at midnight.
    """

    dt = datetime.now(tzinfo)
    return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) 
Example #27
Source File: dag.py    From airflow with Apache License 2.0 5 votes vote down vote up
def get_task_instances(
            self, start_date=None, end_date=None, state=None, session=None):
        if not start_date:
            start_date = (timezone.utcnow() - timedelta(30)).date()
            start_date = timezone.make_aware(
                datetime.combine(start_date, datetime.min.time()))

        tis = session.query(TaskInstance).filter(
            TaskInstance.dag_id == self.dag_id,
            TaskInstance.execution_date >= start_date,
            TaskInstance.task_id.in_([t.task_id for t in self.tasks]),
        )
        # This allows allow_trigger_in_future config to take affect, rather than mandating exec_date <= UTC
        if end_date or not self.allow_future_exec_dates:
            end_date = end_date or timezone.utcnow()
            tis = tis.filter(TaskInstance.execution_date <= end_date)

        if state:
            if isinstance(state, str):
                tis = tis.filter(TaskInstance.state == state)
            else:
                # this is required to deal with NULL values
                if None in state:
                    if all(x is None for x in state):
                        tis = tis.filter(TaskInstance.state.is_(None))
                    else:
                        not_none_state = [s for s in state if s]
                        tis = tis.filter(
                            or_(TaskInstance.state.in_(not_none_state),
                                TaskInstance.state.is_(None))
                        )
                else:
                    tis = tis.filter(TaskInstance.state.in_(state))
        tis = tis.order_by(TaskInstance.execution_date).all()
        return tis 
Example #28
Source File: indy_provider.py    From aries-protocol-test-suite with Apache License 2.0 5 votes vote down vote up
def _append_taa(self, req):
        getTaaReq = await ledger.build_get_txn_author_agreement_request(self.did, None)
        response = await ledger.submit_request(self.pool, getTaaReq)
        taa = (json.loads(response))["result"]["data"]
        if not taa:
            return req
        curTime = int(datetime.combine(date.today(), datetime.min.time()).timestamp())
        req = await ledger.append_txn_author_agreement_acceptance_to_request(req,taa["text"],taa["version"],taa["digest"],"wallet",curTime)
        return req 
Example #29
Source File: idatetime.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def combine(date, time):
        """Return a new datetime object.

        Its date members are equal to the given date object's, and whose time
        and tzinfo members are equal to the given time object's. For any
        datetime object d, d == datetime.combine(d.date(), d.timetz()).
        If date is a datetime object, its time and tzinfo members are ignored.
        """ 
Example #30
Source File: test_datetime.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bug_1028306(self):
        # Trying to compare a date to a datetime should act like a mixed-
        # type comparison, despite that datetime is a subclass of date.
        as_date = date.today()
        as_datetime = datetime.combine(as_date, time())
        self.assertTrue(as_date != as_datetime)
        self.assertTrue(as_datetime != as_date)
        self.assertFalse(as_date == as_datetime)
        self.assertFalse(as_datetime == as_date)
        self.assertRaises(TypeError, lambda: as_date < as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime < as_date)
        self.assertRaises(TypeError, lambda: as_date <= as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime <= as_date)
        self.assertRaises(TypeError, lambda: as_date > as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime > as_date)
        self.assertRaises(TypeError, lambda: as_date >= as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime >= as_date)

        # Neverthelss, comparison should work with the base-class (date)
        # projection if use of a date method is forced.
        self.assertTrue(as_date.__eq__(as_datetime))
        different_day = (as_date.day + 1) % 20 + 1
        self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day)))

        # And date should compare with other subclasses of date.  If a
        # subclass wants to stop this, it's up to the subclass to do so.
        date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
        self.assertEqual(as_date, date_sc)
        self.assertEqual(date_sc, as_date)

        # Ditto for datetimes.
        datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
                                       as_date.day, 0, 0, 0)
        self.assertEqual(as_datetime, datetime_sc)
        self.assertEqual(datetime_sc, as_datetime)