Python datetime.datetime.datetime() Examples
The following are 30
code examples of datetime.datetime.datetime().
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 also want to check out all available functions/classes of the module
datetime.datetime
, or try the search function
.
Example #1
Source File: flowlogs_reader.py From flowlogs-reader with Apache License 2.0 | 7 votes |
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 #2
Source File: __init__.py From asn1tools with MIT License | 7 votes |
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 #3
Source File: _common.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #4
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: __init__.py From pygrametl with BSD 2-Clause "Simplified" License | 6 votes |
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 #6
Source File: flowlogs_reader.py From flowlogs-reader with Apache License 2.0 | 6 votes |
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 #7
Source File: __init__.py From asn1tools with MIT License | 6 votes |
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
Source File: __init__.py From asn1tools with MIT License | 6 votes |
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 #9
Source File: __init__.py From asn1tools with MIT License | 6 votes |
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 #10
Source File: __init__.py From asn1tools with MIT License | 6 votes |
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 #11
Source File: _common.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: _common.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: http.py From recruit with Apache License 2.0 | 6 votes |
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 #14
Source File: api.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: _common.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: _common.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: client.py From clashroyale with MIT License | 6 votes |
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 #18
Source File: http.py From recruit with Apache License 2.0 | 5 votes |
def http_date(timestamp=None): """Formats the time to match the RFC1123 date format. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. :param timestamp: If provided that date is used, otherwise the current. """ return _dump_date(timestamp, " ")
Example #19
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
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 """ return False
Example #20
Source File: http.py From recruit with Apache License 2.0 | 5 votes |
def cookie_date(expires=None): """Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``. :param expires: If provided that date is used, otherwise the current. """ return _dump_date(expires, "-")
Example #21
Source File: http.py From recruit with Apache License 2.0 | 5 votes |
def _dump_date(d, delim): """Used for `http_date` and `cookie_date`.""" if d is None: d = gmtime() elif isinstance(d, datetime): d = d.utctimetuple() elif isinstance(d, (integer_types, float)): d = gmtime(d) return "%s, %02d%s%s%s%s %02d:%02d:%02d GMT" % ( ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[d.tm_wday], d.tm_mday, delim, ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", )[d.tm_mon - 1], delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec, )
Example #22
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def get(self, tzid=None): """ Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. :param tzid: If there is exactly one time zone available, omitting ``tzid`` or passing :py:const:`None` value returns it. Otherwise a valid key (which can be retrieved from :func:`keys`) is required. :raises ValueError: Raised if ``tzid`` is not specified but there are either more or fewer than 1 zone defined. :returns: Returns either a :py:class:`datetime.tzinfo` object representing the relevant time zone or :py:const:`None` if the ``tzid`` was not found. """ if tzid is None: if len(self._vtz) == 0: raise ValueError("no timezones defined") elif len(self._vtz) > 1: raise ValueError("more than one timezone available") tzid = next(iter(self._vtz)) return self._vtz.get(tzid)
Example #23
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule
Example #24
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def is_ambiguous(self, dt, idx=None): """ 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 idx is None: idx = self._find_last_transition(dt) # Calculate the difference in offsets from current to previous timestamp = _datetime_to_timestamp(dt) tti = self._get_ttinfo(idx) if idx is None or idx <= 0: return False od = self._get_ttinfo(idx - 1).offset - tti.offset tt = self._trans_list[idx] # Transition time return timestamp < tt + od
Example #25
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def fromutc(self, dt): """ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone. """ # These isinstance checks are in datetime.tzinfo, so we'll preserve # them, even if we don't care about duck typing. if not isinstance(dt, datetime.datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # First treat UTC as wall time and get the transition we're in. idx = self._find_last_transition(dt, in_utc=True) tti = self._get_ttinfo(idx) dt_out = dt + datetime.timedelta(seconds=tti.offset) fold = self.is_ambiguous(dt_out, idx=idx) return enfold(dt_out, fold=int(fold))
Example #26
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def _isdst(self, dt, fold_naive=True): # We can't use mktime here. It is unstable when deciding if # the hour near to a change is DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above yields the following result: # # >>> import tz, datetime # >>> t = tz.tzlocal() # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRST' # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() # 'BRDT' # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() # 'BRDT' # # Here is a more stable implementation: # if not self._hasdst: return False # Check for ambiguous times: dstval = self._naive_is_dst(dt) fold = getattr(dt, 'fold', None) if self.is_ambiguous(dt): if fold is not None: return not self._fold(dt) else: return True return dstval
Example #27
Source File: __init__.py From pygrametl with BSD 2-Clause "Simplified" License | 5 votes |
def ymdparser(ymdstr): """Convert a string of the form 'yyyy-MM-dd' to a datetime.date. If the input is None, the return value is also None. """ if ymdstr is None: return None (year, month, day) = ymdstr.split('-') return date(int(year), int(month), int(day))
Example #28
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
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 """ return False
Example #29
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def __init__(self, name, offset): self._name = name try: # Allow a timedelta offset = offset.total_seconds() except (TypeError, AttributeError): pass self._offset = datetime.timedelta(seconds=offset)
Example #30
Source File: tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def fromutc(self, dt): """ Fast track version of fromutc() returns the original ``dt`` object for any valid :py:class:`datetime.datetime` object. """ return dt