本文整理汇总了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
示例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
示例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
示例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
示例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))
示例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)
示例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))
示例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
示例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)
示例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
示例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
示例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)
示例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)))
示例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
示例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()