當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.combine方法代碼示例

本文整理匯總了Python中datetime.datetime.combine方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.combine方法的具體用法?Python datetime.combine怎麽用?Python datetime.combine使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.combine方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_class_ops_pytz

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_timestamp.py

示例2: test_class_ops_dateutil

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_timestamp.py

示例3: create_partition

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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) 
開發者ID:MycroftAI,項目名稱:selene-backend,代碼行數:18,代碼來源:api.py

示例4: test_combine

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_datetime.py

示例5: test_schedule_tab

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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") 
開發者ID:Mebus,項目名稱:restatic,代碼行數:23,代碼來源:test_schedule.py

示例6: assertExcelRow

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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) 
開發者ID:rapidpro,項目名稱:casepro,代碼行數:27,代碼來源:test.py

示例7: convert_string_to_datetime

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:AnyBlok,項目名稱:AnyBlok,代碼行數:18,代碼來源:column.py

示例8: fetch_notification_status_for_day

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:alphagov,項目名稱:notifications-api,代碼行數:25,代碼來源:fact_notification_status_dao.py

示例9: fetch_billing_data_for_day

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:alphagov,項目名稱:notifications-api,代碼行數:27,代碼來源:fact_billing_dao.py

示例10: datetime

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:lk-geimfari,項目名稱:mimesis,代碼行數:22,代碼來源:date.py

示例11: process_csv

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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) 
開發者ID:albertogaspar,項目名稱:dts,代碼行數:20,代碼來源:uci_single_households.py

示例12: test_combine

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:24,代碼來源:datetimetester.py

示例13: today

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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)) 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:16,代碼來源:utils.py

示例14: apply

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
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.') 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:offsets.py

示例15: run_scheduler

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import combine [as 別名]
def run_scheduler(self):
        while True:
            interval = 60
            for s in await self.get_service('data_svc').locate('schedules'):
                now = datetime.now().time()
                diff = datetime.combine(date.today(), now) - datetime.combine(date.today(), s.schedule)
                if interval > diff.total_seconds() > 0:
                    self.log.debug('Pulling %s off the scheduler' % s.name)
                    sop = copy.deepcopy(s.task)
                    sop.set_start_details()
                    await self._services.get('data_svc').store(sop)
                    self.loop.create_task(sop.run(self.get_services()))
            await asyncio.sleep(interval) 
開發者ID:mitre,項目名稱:caldera,代碼行數:15,代碼來源:app_svc.py


注:本文中的datetime.datetime.combine方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。