当前位置: 首页>>代码示例>>Python>>正文


Python datetime.datetime方法代码示例

本文整理汇总了Python中datetime.datetime.datetime方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.datetime方法的具体用法?Python datetime.datetime怎么用?Python datetime.datetime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.datetime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def get_datetime(self, timestamp: str, unix=True):
        """Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp
        or a datetime.datetime object

        Parameters
        ---------
        timestamp: str
            A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API
            in the ``created_time`` field for example (eg. 20180718T145906.000Z)
        unix: Optional[bool] = True
            Whether to return a POSIX timestamp (seconds since epoch) or not

        Returns int or datetime.datetime
        """
        time = datetime.strptime(timestamp, '%Y%m%dT%H%M%S.%fZ')
        if unix:
            return int(time.timestamp())
        else:
            return time 
开发者ID:cgrok,项目名称:clashroyale,代码行数:21,代码来源:client.py

示例2: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def __init__(self, limit=20, upper_date_limit=None, lower_date_limit=None):
        """
        :param int limit: The number of data items to process in the current\
        round of processing.

        :param tuple upper_date_limit: The date at which to stop collecting\
        new data. This should be entered as a tuple which can serve as the\
        argument to `datetime.datetime`.\
        E.g. `date_limit=(2015, 4, 1, 12, 40)` for 12:30 pm on April 1 2015.

        :param tuple lower_date_limit: The date at which to stop collecting\
        new data. See `upper_data_limit` for formatting.
        """
        BasicTweetHandler.__init__(self, limit)

        self.upper_date_limit = None
        self.lower_date_limit = None
        if upper_date_limit:
            self.upper_date_limit = datetime(*upper_date_limit, tzinfo=LOCAL)
        if lower_date_limit:
            self.lower_date_limit = datetime(*lower_date_limit, tzinfo=LOCAL)

        self.startingup = True 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:25,代码来源:api.py

示例3: check_date_limit

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def check_date_limit(self, data, verbose=False):
        """
        Validate date limits.
        """
        if self.upper_date_limit or self.lower_date_limit:
            date_fmt = '%a %b %d %H:%M:%S +0000 %Y'
            tweet_date = \
                datetime.strptime(data['created_at'],
                                  date_fmt).replace(tzinfo=UTC)
            if (self.upper_date_limit and tweet_date > self.upper_date_limit) or \
               (self.lower_date_limit and tweet_date < self.lower_date_limit):
                if self.upper_date_limit:
                    message = "earlier"
                    date_limit = self.upper_date_limit
                else:
                    message = "later"
                    date_limit = self.lower_date_limit
                if verbose:
                    print("Date limit {0} is {1} than date of current tweet {2}".\
                      format(date_limit, message, tweet_date))
                self.do_stop = True 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:23,代码来源:api.py

示例4: _generalized_time_to_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def _generalized_time_to_datetime(string):
    length = len(string)

    if '.' in string:
        try:
            return datetime.strptime(string, '%Y%m%d%H%M.%f')
        except ValueError:
            return datetime.strptime(string, '%Y%m%d%H%M%S.%f')
    elif ',' in string:
        try:
            return datetime.strptime(string, '%Y%m%d%H%M,%f')
        except ValueError:
            return datetime.strptime(string, '%Y%m%d%H%M%S,%f')
    elif length == 12:
        return datetime.strptime(string, '%Y%m%d%H%M')
    elif length == 14:
        return datetime.strptime(string, '%Y%m%d%H%M%S')
    else:
        raise ValueError 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:21,代码来源:__init__.py

示例5: utc_time_to_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def utc_time_to_datetime(string):
    """Convert given ASN.1 UTC time string `string` to a
    ``datetime.datetime`` object.

    """

    length = len(string)

    try:
        if string[-1] == 'Z':
            if length == 11:
                return datetime.strptime(string[:-1], '%y%m%d%H%M')
            elif length == 13:
                return datetime.strptime(string[:-1], '%y%m%d%H%M%S')
            else:
                raise ValueError
        elif length == 15:
            return compat.strptime(string, '%y%m%d%H%M%z')
        elif length == 17:
            return compat.strptime(string, '%y%m%d%H%M%S%z')
        else:
            raise ValueError
    except (ValueError, IndexError):
        raise Error(
            "Expected a UTC time string, but got '{}'.".format(string)) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:27,代码来源:__init__.py

示例6: utc_time_from_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def utc_time_from_datetime(date):
    """Convert given ``datetime.datetime`` object `date` to an ASN.1 UTC
    time string.

    """

    fmt = '%y%m%d%H%M'

    if date.second > 0:
        fmt += '%S'

    if date.tzinfo is None:
        fmt += 'Z'
    else:
        fmt += '%z'

    return date.strftime(fmt) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:19,代码来源:__init__.py

示例7: restricted_utc_time_to_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def restricted_utc_time_to_datetime(string):
    """Convert given restricted ASN.1 UTC time string `string` to a
    ``datetime.datetime`` object.

    """

    try:
        if string[-1] != 'Z':
            raise ValueError

        if len(string) != 13:
            raise ValueError

        return datetime.strptime(string[:-1], '%y%m%d%H%M%S')
    except (ValueError, IndexError):
        raise Error(
            "Expected a restricted UTC time string, but got '{}'.".format(
                string)) 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:20,代码来源:__init__.py

示例8: generalized_time_from_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def generalized_time_from_datetime(date):
    """Convert given ``datetime.datetime`` object `date` to an ASN.1
    generalized time string.

    """

    if date.second == 0:
        if date.microsecond > 0:
            string = date.strftime('%Y%m%d%H%M.%f').rstrip('0')
        else:
            string = date.strftime('%Y%m%d%H%M')
    else:
        if date.microsecond > 0:
            string = date.strftime('%Y%m%d%H%M%S.%f').rstrip('0')
        else:
            string = date.strftime('%Y%m%d%H%M%S')

    if date.tzinfo is not None:
        if date.utcoffset():
            string += date.strftime('%z')
        else:
            string += 'Z'

    return string 
开发者ID:eerimoq,项目名称:asn1tools,代码行数:26,代码来源:__init__.py

示例9: enfold

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def enfold(dt, fold=1):
        """
        Provides a unified interface for assigning the ``fold`` attribute to
        datetimes both before and after the implementation of PEP-495.

        :param fold:
            The value for the ``fold`` attribute in the returned datetime. This
            should be either 0 or 1.

        :return:
            Returns an object for which ``getattr(dt, 'fold', 0)`` returns
            ``fold`` for all versions of Python. In versions prior to
            Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
            subclass of :py:class:`datetime.datetime` with the ``fold``
            attribute added, if ``fold`` is 1.

        .. versionadded:: 2.6.0
        """
        return dt.replace(fold=fold) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:21,代码来源:_common.py

示例10: is_ambiguous

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def is_ambiguous(self, dt):
        """
        Whether or not the "wall time" of a given datetime is ambiguous in this
        zone.

        :param dt:
            A :py:class:`datetime.datetime`, naive or time zone aware.


        :return:
            Returns ``True`` if ambiguous, ``False`` otherwise.

        .. versionadded:: 2.6.0
        """

        dt = dt.replace(tzinfo=self)

        wall_0 = enfold(dt, fold=0)
        wall_1 = enfold(dt, fold=1)

        same_offset = wall_0.utcoffset() == wall_1.utcoffset()
        same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)

        return same_dt and not same_offset 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:26,代码来源:_common.py

示例11: _fold_status

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def _fold_status(self, dt_utc, dt_wall):
        """
        Determine the fold status of a "wall" datetime, given a representation
        of the same datetime as a (naive) UTC datetime. This is calculated based
        on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all
        datetimes, and that this offset is the actual number of hours separating
        ``dt_utc`` and ``dt_wall``.

        :param dt_utc:
            Representation of the datetime as UTC

        :param dt_wall:
            Representation of the datetime as "wall time". This parameter must
            either have a `fold` attribute or have a fold-naive
            :class:`datetime.tzinfo` attached, otherwise the calculation may
            fail.
        """
        if self.is_ambiguous(dt_wall):
            delta_wall = dt_wall - dt_utc
            _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))
        else:
            _fold = 0

        return _fold 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:26,代码来源:_common.py

示例12: fromutc

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def fromutc(self, dt):
        """
        Given a timezone-aware datetime in a given timezone, calculates a
        timezone-aware datetime in a new timezone.

        Since this is the one time that we *know* we have an unambiguous
        datetime object, we take this opportunity to determine whether the
        datetime is ambiguous and in a "fold" state (e.g. if it's the first
        occurance, chronologically, of the ambiguous datetime).

        :param dt:
            A timezone-aware :class:`datetime.datetime` object.
        """
        dt_wall = self._fromutc(dt)

        # Calculate the fold status given the two datetimes.
        _fold = self._fold_status(dt, dt_wall)

        # Set the default fold value for ambiguous dates
        return enfold(dt_wall, fold=_fold) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:22,代码来源:_common.py

示例13: is_ambiguous

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def is_ambiguous(self, dt):
        """
        Whether or not the "wall time" of a given datetime is ambiguous in this
        zone.

        :param dt:
            A :py:class:`datetime.datetime`, naive or time zone aware.


        :return:
            Returns ``True`` if ambiguous, ``False`` otherwise.

        .. versionadded:: 2.6.0
        """
        naive_dst = self._naive_is_dst(dt)
        return (not naive_dst and
                (naive_dst != self._naive_is_dst(dt - self._dst_saved))) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:19,代码来源:tz.py

示例14: datereader

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def datereader(dateattribute, parsingfunction=ymdparser):
    """Return a function that converts a certain dict member to a datetime.date

       When setting, fromfinder for a tables.SlowlyChangingDimension, this
       method can be used for generating a function that picks the relevant
       dictionary member from each row and converts it.

       Arguments:
           
       - dateattribute: the attribute the generated function should read
       - parsingfunction: the parsing function that converts the string
         to a datetime.date
    """
    def readerfunction(targetconnection, row, namemapping={}):
        atttouse = (namemapping.get(dateattribute) or dateattribute)
        return parsingfunction(row[atttouse])  # a datetime.date

    return readerfunction 
开发者ID:chrthomsen,项目名称:pygrametl,代码行数:20,代码来源:__init__.py

示例15: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import datetime [as 别名]
def __init__(
        self,
        client_type,
        region_name=None,
        profile_name=None,
        start_time=None,
        end_time=None,
        boto_client_kwargs=None,
        boto_client=None,
    ):
        # Get a boto3 client with which to perform queries
        if boto_client is not None:
            self.boto_client = boto_client
        else:
            self.boto_client = self._get_client(
                client_type, region_name, profile_name, boto_client_kwargs
            )

        # If no time filters are given use the last hour
        now = datetime.utcnow()
        self.start_time = start_time or now - timedelta(hours=1)
        self.end_time = end_time or now

        # Initialize the iterator
        self.iterator = self._reader() 
开发者ID:obsrvbl,项目名称:flowlogs-reader,代码行数:27,代码来源:flowlogs_reader.py


注:本文中的datetime.datetime.datetime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。