Python datetime.datetime.datetime() Examples

The following are 30 code examples for showing how to use datetime.datetime.datetime(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .

Example 1
Project: clashroyale   Author: cgrok   File: client.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: razzy-spinner   Author: rafasashi   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 3
Project: razzy-spinner   Author: rafasashi   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 4
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 6 votes vote down vote up
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)) 
Example 6
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 6 votes vote down vote up
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) 
Example 7
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 6 votes vote down vote up
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)) 
Example 8
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 6 votes vote down vote up
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 
Example 9
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 10
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 11
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 13
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
        """
        if not self.hasdst:
            return False

        start, end = self.transitions(dt.year)

        dt = dt.replace(tzinfo=None)
        return (end <= dt < end + self._dst_base_offset) 
Example 14
Project: plugin.video.emby   Author: MediaBrowser   File: tz.py    License: GNU General Public License v3.0 6 votes vote down vote up
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))) 
Example 15
Project: pygrametl   Author: chrthomsen   File: __init__.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example 16
Project: flowlogs-reader   Author: obsrvbl   File: flowlogs_reader.py    License: Apache License 2.0 6 votes vote down vote up
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() 
Example 17
Project: flowlogs-reader   Author: obsrvbl   File: flowlogs_reader.py    License: Apache License 2.0 6 votes vote down vote up
def _get_keys(self, prefix):
        # S3 keys have a file name like:
        # account_vpcflowlogs_region_flow-logs-id_datetime_hash.log.gz
        # Yield the keys for files relevant to our time range
        paginator = self.boto_client.get_paginator('list_objects_v2')
        all_pages = paginator.paginate(Bucket=self.bucket, Prefix=prefix)
        for page in all_pages:
            for item in page.get('Contents', []):
                key = item['Key']
                file_name = basename(key)
                try:
                    dt = datetime.strptime(
                        file_name.rsplit('_', 2)[1], '%Y%m%dT%H%MZ'
                    )
                except (IndexError, ValueError):
                    continue

                if self.start_time <= dt < self.end_time:
                    yield key 
Example 18
Project: recruit   Author: Frank-qlu   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def dump_age(age=None):
    """Formats the duration as a base-10 integer.

    :param age: should be an integer number of seconds,
                a :class:`datetime.timedelta` object, or,
                if the age is unknown, `None` (default).
    """
    if age is None:
        return
    if isinstance(age, timedelta):
        # do the equivalent of Python 2.7's timedelta.total_seconds(),
        # but disregarding fractional seconds
        age = age.seconds + (age.days * 24 * 3600)

    age = int(age)
    if age < 0:
        raise ValueError("age cannot be negative")

    return str(age) 
Example 19
Project: clashroyale   Author: cgrok   File: client.py    License: MIT License 5 votes vote down vote up
def _resolve_cache(self, url, **params):
        bucket = url + (('?' + urlencode(params)) if params else '')
        cached_data = self.cache.get(bucket)
        if not cached_data:
            return None
        last_updated = from_timestamp(cached_data['c_timestamp'])
        if (datetime.utcnow() - last_updated).total_seconds() < self.cache_reset:
            ret = (cached_data['data'], True, last_updated, None)
            if self.is_async:
                return self._wrap_coro(ret)
            return ret
        return None 
Example 20
Project: clashroyale   Author: cgrok   File: client.py    License: MIT License 5 votes vote down vote up
def _raise_for_status(self, resp, text, *, method=None):
        try:
            data = json.loads(text)
        except json.JSONDecodeError:
            data = text
        code = getattr(resp, 'status', None) or getattr(resp, 'status_code')
        log.debug(self.REQUEST_LOG.format(method=method or resp.request_info.method, url=resp.url, text=text, status=code))
        if self.error_debug:
            raise ServerError(resp, data)
        if 300 > code >= 200:  # Request was successful
            if self.using_cache:
                cached_data = {
                    'c_timestamp': datetime.utcnow().timestamp(),
                    'data': data
                }
                self.cache[str(resp.url)] = cached_data
            return data, False, datetime.utcnow(), resp  # value, cached, last_updated, response
        if code == 400:
            raise BadRequest(resp, data)
        if code in (401, 403):  # Unauthorized request - Invalid token
            raise Unauthorized(resp, data)
        if code == 404:  # Tag not found
            raise NotFoundError(resp, data)
        if code == 429:
            raise RatelimitError(resp, data)
        if code == 503:  # Maintainence
            raise ServerError(resp, data)

        raise UnexpectedError(resp, data) 
Example 21
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_load(self, value, *, context, **kwargs):
        if value is None:
            return None
        dt = datetime.datetime.strptime(value, FIXED_ISO8601_FORMAT)
        # we assume all stored values are utc, so we simply force timezone to utc
        # without changing the day/time values
        return dt.replace(tzinfo=datetime.timezone.utc) 
Example 22
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        dt = value.astimezone(tz=datetime.timezone.utc)
        return dt.strftime(FIXED_ISO8601_FORMAT) 
Example 23
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_load(self, value, *, context, **kwargs):
        if value is None:
            return None
        value = super().dynamo_load(value, context=context, **kwargs)
        # we assume all stored values are utc, so we simply force timezone to utc
        # without changing the day/time values
        return datetime.datetime.fromtimestamp(value, tz=datetime.timezone.utc) 
Example 24
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        value = value.timestamp()
        return super().dynamo_dump(value, context=context, **kwargs) 
Example 25
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 5 votes vote down vote up
def restricted_utc_time_from_datetime(date):
    """Convert given ``datetime.datetime`` object `date` to an restricted
    ASN.1 UTC time string.

    """

    if date.tzinfo is not None:
        date -= date.utcoffset()

    return date.strftime('%y%m%d%H%M%S') + 'Z' 
Example 26
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 5 votes vote down vote up
def restricted_generalized_time_to_datetime(string):
    """Convert given restricted ASN.1 generalized time string `string` to
    a ``datetime.datetime`` object.

    """

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

        if '.' in string:
            if string[-2] == '0':
                raise ValueError

            if string[14] != '.':
                raise ValueError

            return datetime.strptime(string[:-1], '%Y%m%d%H%M%S.%f')
        elif len(string) != 15:
            raise ValueError

        return datetime.strptime(string[:-1], '%Y%m%d%H%M%S')
    except (ValueError, IndexError):
        raise Error(
            "Expected a restricted generalized time string, but got '{}'.".format(
                string)) 
Example 27
Project: asn1tools   Author: eerimoq   File: __init__.py    License: MIT License 5 votes vote down vote up
def restricted_generalized_time_from_datetime(date):
    """Convert given ``datetime.datetime`` object `date` to an restricted
    ASN.1 generalized time string.

    """

    if date.tzinfo is not None:
        date -= date.utcoffset()

    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')

    return string + 'Z' 
Example 28
Project: instaloader   Author: instaloader   File: structures.py    License: MIT License 5 votes vote down vote up
def date_local(self) -> datetime:
        """Timestamp when the post was created (local time zone)."""
        return datetime.fromtimestamp(self._node["date"]
                                      if "date" in self._node
                                      else self._node["taken_at_timestamp"]) 
Example 29
Project: instaloader   Author: instaloader   File: structures.py    License: MIT License 5 votes vote down vote up
def date_utc(self) -> datetime:
        """Timestamp when the post was created (UTC)."""
        return datetime.utcfromtimestamp(self._node["date"]
                                         if "date" in self._node
                                         else self._node["taken_at_timestamp"]) 
Example 30
Project: instaloader   Author: instaloader   File: structures.py    License: MIT License 5 votes vote down vote up
def date(self) -> datetime:
        """Synonym to :attr:`~Post.date_utc`"""
        return self.date_utc