本文整理汇总了Python中datetime.datetime.timedelta方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.timedelta方法的具体用法?Python datetime.timedelta怎么用?Python datetime.timedelta使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.datetime
的用法示例。
在下文中一共展示了datetime.timedelta方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_simple_model_with_annual_licence_multi_year
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def test_simple_model_with_annual_licence_multi_year(simple_linear_model):
""" Test the AnnualLicense over multiple years
"""
import pandas as pd
import datetime, calendar
m = simple_linear_model
# Modify model to run for 3 years of non-leap years at 30 day time-step.
m.timestepper.start = pd.to_datetime('2017-1-1')
m.timestepper.end = pd.to_datetime('2020-1-1')
m.timestepper.delta = datetime.timedelta(30)
annual_total = 365.0
lic = AnnualLicense(m, m.nodes["Input"], annual_total)
# Apply licence to the model
m.nodes["Input"].max_flow = lic
m.nodes["Output"].max_flow = 10.0
m.nodes["Output"].cost = -10.0
m.setup()
for i in range(len(m.timestepper)):
m.step()
days_in_year = 365 + int(calendar.isleap(m.timestepper.current.datetime.year))
assert_allclose(m.nodes["Output"].flow, annual_total/days_in_year)
示例2: parse_age
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def parse_age(value=None):
"""Parses a base-10 integer count of seconds into a timedelta.
If parsing fails, the return value is `None`.
:param value: a string consisting of an integer represented in base-10
:return: a :class:`datetime.timedelta` object or `None`.
"""
if not value:
return None
try:
seconds = int(value)
except ValueError:
return None
if seconds < 0:
return None
try:
return timedelta(seconds=seconds)
except OverflowError:
return None
示例3: dump_age
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
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)
示例4: stop
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def stop(self):
"""Stop timer and print info message
The info message will be only printed if `Timer.verbose` is *true*.
Returns:
A timedelta object.
"""
if self.starttime is None:
raise ValueError("Timer has not been started yet!")
self.endtime = time.time()
dt = timedelta(seconds=self.endtime - self.starttime)
# If no additional information is specified add default information
# to make the output more readable.
if self.info is None:
self.info = 'elapsed time'
if self.verbose:
# Connect additional information and measured time for output.
print('{info}: {time}'.format(info=self.info, time=dt))
return dt
示例5: create_sas_token
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def create_sas_token(key_name, shared_access_key, scope, expiry=timedelta(hours=1)):
"""Create a SAS token.
:param key_name: The username/key name/policy name for the token.
:type key_name: bytes
:param shared_access_key: The shared access key to generate the token from.
:type shared_access_key: bytes
:param scope: The token permissions scope.
:type scope: bytes
:param expiry: The lifetime of the generated token. Default is 1 hour.
:type expiry: ~datetime.timedelta
:rtype: bytes
"""
shared_access_key = base64.b64encode(shared_access_key)
abs_expiry = int(time.time()) + expiry.seconds
return c_uamqp.create_sas_token(shared_access_key, scope, key_name, abs_expiry)
示例6: dump_age
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
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)
示例7: total_seconds
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def total_seconds(td):
"""
Given a timedelta (*td*) return an integer representing the equivalent of
Python 2.7's :meth:`datetime.timdelta.total_seconds`.
"""
return (((
td.microseconds +
(td.seconds + td.days * 24 * 3600) * 10**6) / 10**6))
# NOTE: This is something I'm investigating as a way to use the new go_async
# module. A work-in-progress. Ignore for now...
示例8: timeout
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def timeout(self):
"""
A `property` that controls how long a key will last before being
automatically removed. May be be given as a `datetime.timedelta`
object or a string like, "1d", "30s" (will be passed through the
`convert_to_timedelta` function).
"""
if not hasattr(self, "_timeout"):
self._timeout = timedelta(hours=1) # Default is 1-hour timeout
return self._timeout
示例9: interval
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def interval(self):
"""
A `property` that controls how often we check for expired keys. May be
given as milliseconds (integer), a `datetime.timedelta` object, or a
string like, "1d", "30s" (will be passed through the
`convert_to_timedelta` function).
"""
if not hasattr(self, "_interval"):
self._interval = 10000 # Default is every 10 seconds
return self._interval
示例10: __init__
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
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)
示例11: fromutc
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
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))
示例12: parse_date
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def parse_date(value):
"""Parse one of the following date formats into a datetime object:
.. sourcecode:: text
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
If parsing fails the return value is `None`.
:param value: a string with a supported date format.
:return: a :class:`datetime.datetime` object.
"""
if value:
t = parsedate_tz(value.strip())
if t is not None:
try:
year = t[0]
# unfortunately that function does not tell us if two digit
# years were part of the string, or if they were prefixed
# with two zeroes. So what we do is to assume that 69-99
# refer to 1900, and everything below to 2000
if year >= 0 and year <= 68:
year += 2000
elif year >= 69 and year <= 99:
year += 1900
return datetime(*((year,) + t[1:7])) - timedelta(seconds=t[-1] or 0)
except (ValueError, OverflowError):
return None
示例13: test_repr
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def test_repr(self):
assert repr(self.offset) == '<BusinessDay>'
assert repr(self.offset2) == '<2 * BusinessDays>'
if compat.PY37:
expected = '<BusinessDay: offset=datetime.timedelta(days=1)>'
else:
expected = '<BusinessDay: offset=datetime.timedelta(1)>'
assert repr(self.offset + timedelta(1)) == expected
示例14: test_with_offset
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def test_with_offset(self):
offset = self.offset + timedelta(hours=2)
assert (self.d + offset) == datetime(2008, 1, 2, 2)
示例15: test_offset
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import timedelta [as 别名]
def test_offset(self):
# Saturday
last_sat = datetime(2013, 8, 31)
next_sat = datetime(2013, 9, 28)
offset_sat = LastWeekOfMonth(n=1, weekday=5)
one_day_before = (last_sat + timedelta(days=-1))
assert one_day_before + offset_sat == last_sat
one_day_after = (last_sat + timedelta(days=+1))
assert one_day_after + offset_sat == next_sat
# Test On that day
assert last_sat + offset_sat == next_sat
# Thursday
offset_thur = LastWeekOfMonth(n=1, weekday=3)
last_thurs = datetime(2013, 1, 31)
next_thurs = datetime(2013, 2, 28)
one_day_before = last_thurs + timedelta(days=-1)
assert one_day_before + offset_thur == last_thurs
one_day_after = last_thurs + timedelta(days=+1)
assert one_day_after + offset_thur == next_thurs
# Test on that day
assert last_thurs + offset_thur == next_thurs
three_before = last_thurs + timedelta(days=-3)
assert three_before + offset_thur == last_thurs
two_after = last_thurs + timedelta(days=+2)
assert two_after + offset_thur == next_thurs
offset_sunday = LastWeekOfMonth(n=1, weekday=WeekDay.SUN)
assert datetime(2013, 7, 31) + offset_sunday == datetime(2013, 8, 25)