当前位置: 首页>>代码示例>>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;未经允许,请勿转载。