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


Python datetime.datetime方法代碼示例

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


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

示例1: getGeneralizedTime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def getGeneralizedTime(cls, dateString):
        year = int(dateString[0:4])
        month = int(dateString[4:6])
        day = int(dateString[6:8])
        hour = int(dateString[8:10])
        minute = int(dateString[10:12])
        #If UTC time.
        if dateString.endsWith("Z"):
            if len(dateString) > 13:
                second = int(dateString[12:14])
            return datetime(year, month, day, hour, minute, second, 0, tzinfo=GXTimeZone(0))

        if len(dateString) > 17:
            second = int(dateString.substring(12, 14))
        tz = dateString[dateString.length() - 4:]
        return datetime(year, month, day, hour, minute, second, 0, tzinfo=GXTimeZone(tz)) 
開發者ID:Gurux,項目名稱:Gurux.DLMS.Python,代碼行數:18,代碼來源:_GXCommon.py

示例2: __getDateTime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def __getDateTime(cls, value):
        dt = None
        if isinstance(value, (GXDateTime)):
            dt = value
        elif isinstance(value, (datetime, str)):
            dt = GXDateTime(value)
            dt.skip |= DateTimeSkips.MILLISECOND
        else:
            raise ValueError("Invalid date format.")
        return dt

    #
    # Convert date time to DLMS bytes.
    #
    # buff
    # Byte buffer where data is write.
    # value
    # Added value.
    # 
開發者ID:Gurux,項目名稱:Gurux.DLMS.Python,代碼行數:21,代碼來源:_GXCommon.py

示例3: test_get_status_summary

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def test_get_status_summary(mock_trial_results):
    """Test the status summary based on the trial results."""
    expected = {
        "SURVIVED": 1,
        "DETECTED": 1,
        "ERROR": 1,
        "UNKNOWN": 1,
        "TIMEOUT": 1,
        "TOTAL RUNS": 5,
        "RUN DATETIME": str(datetime(2019, 1, 1)),
    }

    result = get_status_summary(mock_trial_results)
    print(expected)

    assert result == expected 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:18,代碼來源:test_report.py

示例4: timestamp_parameter

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def timestamp_parameter(timestamp, allow_none=True):

    if timestamp is None:
        if allow_none:
            return None
        raise ValueError("Timestamp value cannot be None")

    if isinstance(timestamp, datetime):
        return timestamp.isoformat()

    if isinstance(timestamp, basestring):
        if not ISO_8601.match(timestamp):
            raise ValueError(("Invalid timestamp: %s is not a valid ISO-8601"
                              " formatted date") % timestamp)
        return timestamp

    raise ValueError("Cannot accept type %s for timestamp" % type(timestamp)) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:19,代碼來源:utils.py

示例5: ensure_datetime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def ensure_datetime(obj):
    """Return the object if it is a datetime-like object

    Parameters
    ----------
    obj : Object to be tested.

    Returns
    -------
    The original object if it is a datetime-like object

    Raises
    ------
    TypeError if `obj` is not datetime-like
    """
    _VALID_TYPES = (str, datetime.datetime, cftime.datetime,
                    np.datetime64)
    if isinstance(obj, _VALID_TYPES):
        return obj
    raise TypeError("datetime-like object required.  "
                    "Type given: {}".format(type(obj))) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:23,代碼來源:times.py

示例6: datetime_or_default

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def datetime_or_default(date, default):
    """Return a datetime-like object or a default.

    Parameters
    ----------
    date : `None` or datetime-like object or str
    default : The value to return if `date` is `None`

    Returns
    -------
    `default` if `date` is `None`, otherwise returns the result of
    `utils.times.ensure_datetime(date)`

    """
    if date is None:
        return default
    else:
        return ensure_datetime(date) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:20,代碼來源:times.py

示例7: recursive_test_params

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def recursive_test_params():
    basic_params = {
        'proj': example_proj,
        'model': example_model,
        'run': example_run,
        'var': condensation_rain,
        'date_range': (datetime.datetime(4, 1, 1),
                       datetime.datetime(6, 12, 31)),
        'intvl_in': 'monthly',
        'dtype_in_time': 'ts'
    }
    recursive_params = basic_params.copy()

    recursive_condensation_rain = Var(
        name='recursive_condensation_rain',
        variables=(precip, convection_rain), func=lambda x, y: x - y,
        def_time=True)
    recursive_params['var'] = recursive_condensation_rain

    yield (basic_params, recursive_params)

    _clean_test_direcs() 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:24,代碼來源:test_calc_basic.py

示例8: download_bill

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def download_bill(self, bill_date, bill_type="ALL", device_info=None):
        """
        下載對賬單

        :param bill_date: 下載對賬單的日期
        :param bill_type: 賬單類型,ALL,返回當日所有訂單信息,默認值
                          SUCCESS,返回當日成功支付的訂單,
                          REFUND,返回當日退款訂單,
                          REVOKED,已撤銷的訂單
        :param device_info: 微信支付分配的終端設備號,填寫此字段,隻下載該設備號的對賬單
        :return: 返回的結果數據
        """
        if isinstance(bill_date, (datetime, date)):
            bill_date = bill_date.strftime("%Y%m%d")

        data = {
            "appid": self.appid,
            "bill_date": bill_date,
            "bill_type": bill_type,
            "device_info": device_info,
        }
        return self._post("pay/downloadbill", data=data) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:24,代碼來源:tools.py

示例9: download_fundflow

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def download_fundflow(self, bill_date, account_type="Basic", tar_type=None):
        """
        下載資金賬單
        https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_18&index=7

        :param bill_date: 下載對賬單的日期
        :param account_type: 賬單的資金來源賬戶
                             Basic  基本賬戶
                             Operation 運營賬戶
                             Fees 手續費賬戶
        :param tar_type: 非必傳參數,固定值:GZIP,返回格式為.gzip的壓縮包賬單。
                         不傳則默認為數據流形式。
        """
        if isinstance(bill_date, (datetime, date)):
            bill_date = bill_date.strftime("%Y%m%d")

        data = {
            "appid": self.appid,
            "bill_date": bill_date,
            "account_type": account_type,
            "sign_type": "HMAC-SHA256",
        }
        if tar_type is not None:
            data["tar_type"] = tar_type
        return self._post("pay/downloadfundflow", data=data) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:27,代碼來源:tools.py

示例10: get_records

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def get_records(self, start_time, end_time, msgid=1, number=10000):
        """
        獲取客服聊天記錄

        :param start_time: 查詢開始時間,UNIX 時間戳
        :param end_time: 查詢結束時間,UNIX 時間戳,每次查詢不能跨日查詢
        :param msgid: 消息id順序從小到大,從1開始
        :param number: 每次獲取條數,最多10000條

        :return: 返回的 JSON 數據包
        """
        if isinstance(start_time, datetime.datetime):
            start_time = time.mktime(start_time.timetuple())
        if isinstance(end_time, datetime.datetime):
            end_time = time.mktime(end_time.timetuple())
        record_data = {
            "starttime": int(start_time),
            "endtime": int(end_time),
            "msgid": msgid,
            "number": number,
        }
        res = self._post("https://api.weixin.qq.com/customservice/msgrecord/getmsglist", data=record_data,)
        return res 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:25,代碼來源:customservice.py

示例11: list_statistics

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def list_statistics(self, begin_date, end_date, shop_id=-1):
        """
        Wi-Fi數據統計

        詳情請參考
        http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html

        :param begin_date: 起始日期時間,最長時間跨度為30天
        :param end_date: 結束日期時間戳,最長時間跨度為30天
        :param shop_id: 可選,門店 ID,按門店ID搜索,-1為總統計
        :return: 返回的 JSON 數據包
        """
        if isinstance(begin_date, (datetime, date)):
            begin_date = begin_date.strftime("%Y-%m-%d")
        if isinstance(end_date, (datetime, date)):
            end_date = end_date.strftime("%Y-%m-%d")
        res = self._post(
            "statistics/list",
            data={"begin_date": begin_date, "end_date": end_date, "shop_id": shop_id},
            result_processor=lambda x: x["data"],
        )
        return res 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:24,代碼來源:wifi.py

示例12: test_qualification_verify_fail_event

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def test_qualification_verify_fail_event(self):
        from wechatpy.events import QualificationVerifyFailEvent

        xml = """
        <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[FromUser]]></FromUserName>
        <CreateTime>1442401156</CreateTime>
        <MsgType><![CDATA[event]]></MsgType>
        <Event><![CDATA[qualification_verify_fail]]></Event>
        <FailTime>1442401122</FailTime>
        <FailReason><![CDATA[by time]]></FailReason>
        </xml>"""
        event = parse_message(xml)
        self.assertTrue(isinstance(event, QualificationVerifyFailEvent))
        self.assertTrue(isinstance(event.fail_time, datetime))
        self.assertEqual(event.fail_reason, "by time") 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:19,代碼來源:test_events.py

示例13: test_naming_verify_fail_event

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def test_naming_verify_fail_event(self):
        from wechatpy.events import NamingVerifyFailEvent

        xml = """
        <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[FromUser]]></FromUserName>
        <CreateTime>1442401061</CreateTime>
        <MsgType><![CDATA[event]]></MsgType>
        <Event><![CDATA[naming_verify_fail]]></Event>
        <FailTime>1442401061</FailTime>
        <FailReason><![CDATA[by time]]></FailReason>
        </xml>"""
        event = parse_message(xml)
        self.assertTrue(isinstance(event, NamingVerifyFailEvent))
        self.assertTrue(isinstance(event.fail_time, datetime))
        self.assertEqual(event.fail_reason, "by time") 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:19,代碼來源:test_events.py

示例14: update

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def update(self):
        self.data['events'] = []
        self.tzutc = tz.tzutc()
        self.tzlocal = tz.tzlocal()
        urls, colors = [], {}
        for cal in self._iter_calendars():
            urls.append(cal.url)
            colors[cal.url] = cal.color
        for result in utils.iter_responses(urls, timeout=5):
            response = result.get('response')
            if response:
                ical = Calendar.from_ical(response.read().decode('utf-8'))
                color = colors[result.get('url')]
                self.data['events'] += self._parse_events(ical, color)
        self.data['events'] = sorted(self.data['events'], key=lambda e:e['start'])
        # Calculate time to next event
        now = datetime.datetime.now()
        next = [e for e in self.data['events'] if e['start'] > now][0]['start'] if self.data['events'] else self.DELTANONE
        if next < now + datetime.timedelta(seconds=self.DEFAULT_INTERVAL*1.5): self.data['next'] = 'Now'
        else: self.data['next'] = utils.natural_time(next-now, 1)
        super(Plugin, self).update() 
開發者ID:pkkid,項目名稱:pkmeter,代碼行數:23,代碼來源:gcal.py

示例15: _parse_events

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import datetime [as 別名]
def _parse_events(self, ical, color):
        events = []
        today = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
        title = ical.get('x-wr-calname', ical.get('version', ''))
        for event in ical.walk():
            if event.name == "VEVENT":
                start = self._event_start(event)
                if today <= start <= today + datetime.timedelta(days=14):
                    events.append({
                        'title': event.get('summary'),
                        'calendar': title,
                        'color': color,
                        'start': start,
                        'where': event.get('location'),
                        'status': event.get('description'),
                    })
        return events 
開發者ID:pkkid,項目名稱:pkmeter,代碼行數:19,代碼來源:gcal.py


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