本文整理匯總了Python中datetime.datetime.replace方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.replace方法的具體用法?Python datetime.replace怎麽用?Python datetime.replace使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime.datetime
的用法示例。
在下文中一共展示了datetime.replace方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_time
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def _get_time(time, tzinfo=None):
"""
Get a timezoned time from a given instant.
.. warning:: The return values of this function may depend on the system clock.
:param time: time, datetime or None
:rtype: time
"""
if time is None:
time = datetime.utcnow()
elif isinstance(time, number_types):
time = datetime.utcfromtimestamp(time)
if time.tzinfo is None:
time = time.replace(tzinfo=UTC)
if isinstance(time, datetime):
if tzinfo is not None:
time = time.astimezone(tzinfo)
if hasattr(tzinfo, 'normalize'): # pytz
time = tzinfo.normalize(time)
time = time.timetz()
elif tzinfo is not None:
time = time.replace(tzinfo=tzinfo)
return time
示例2: _format_fallback_interval
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def _format_fallback_interval(start, end, skeleton, tzinfo, locale):
if skeleton in locale.datetime_skeletons: # Use the given skeleton
format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale)
elif all((isinstance(d, date) and not isinstance(d, datetime)) for d in (start, end)): # Both are just dates
format = lambda dt: format_date(dt, locale=locale)
elif all((isinstance(d, time) and not isinstance(d, date)) for d in (start, end)): # Both are times
format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale)
else:
format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale)
formatted_start = format(start)
formatted_end = format(end)
if formatted_start == formatted_end:
return format(start)
return (
locale.interval_formats.get(None, "{0}-{1}").
replace("{0}", formatted_start).
replace("{1}", formatted_end)
)
示例3: untokenize_pattern
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def untokenize_pattern(tokens):
"""
Turn a date format pattern token stream back into a string.
This is the reverse operation of ``tokenize_pattern``.
:type tokens: Iterable[tuple]
:rtype: str
"""
output = []
for tok_type, tok_value in tokens:
if tok_type == "field":
output.append(tok_value[0] * tok_value[1])
elif tok_type == "chars":
if not any(ch in PATTERN_CHARS for ch in tok_value): # No need to quote
output.append(tok_value)
else:
output.append("'%s'" % tok_value.replace("'", "''"))
return "".join(output)
示例4: __init__
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def __init__(self, value, locale):
assert isinstance(value, (date, datetime, time))
if isinstance(value, (datetime, time)) and value.tzinfo is None:
value = value.replace(tzinfo=UTC)
self.value = value
self.locale = Locale.parse(locale)
示例5: get_day_of_year
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def get_day_of_year(self, date=None):
if date is None:
date = self.value
return (date - date.replace(month=1, day=1)).days + 1
示例6: wallet_send_grams
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def wallet_send_grams(self, public_key, secret, dest_address, seq_no: int, valid_until: datetime, amount, message=''):
"""
TL Spec
wallet.sendGrams private_key:inputKey destination:accountAddress seqno:int32 valid_until:int53 amount:int64 message:bytes
= SendGramsResult;
inputKey key:key local_password:secureBytes = InputKey;
key public_key:string secret:secureBytes = Key;
accountAddress account_address:string = AccountAddress;
sendGramsResult sent_until:int53 = SendGramsResult;
:param public_key:
:param secret:
:param dest_address:
:param seq_no:
:param valid_until:
:param amount:
:param message:
:return:
"""
if valid_until.tzname() is None:
valid_until = datetime.replace(tzinfo=timezone.utc)
valid_until_ts = valid_until.timestamp()
data = {
'@type': 'wallet.sendGrams',
'private_key': {
'key': {
'public_key': public_key,
'secret': secret
}
},
'destination': {
'account_address': dest_address
},
'seqno': seq_no,
'valid_until': valid_until_ts,
'amount': amount,
'message': message
}
r = self._t_local.tonlib.ton_async_execute(data)
return r
示例7: _ensure_datetime_tzinfo
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def _ensure_datetime_tzinfo(datetime, tzinfo=None):
"""
Ensure the datetime passed has an attached tzinfo.
If the datetime is tz-naive to begin with, UTC is attached.
If a tzinfo is passed in, the datetime is normalized to that timezone.
>>> _ensure_datetime_tzinfo(datetime(2015, 1, 1)).tzinfo.zone
'UTC'
>>> tz = get_timezone("Europe/Stockholm")
>>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour
14
:param datetime: Datetime to augment.
:param tzinfo: Optional tznfo.
:return: datetime with tzinfo
:rtype: datetime
"""
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=UTC)
if tzinfo is not None:
datetime = datetime.astimezone(get_timezone(tzinfo))
if hasattr(tzinfo, 'normalize'): # pytz
datetime = tzinfo.normalize(datetime)
return datetime
示例8: format_datetime
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def format_datetime(datetime=None, format='medium', tzinfo=None,
locale=LC_TIME):
r"""Return a date formatted according to the given pattern.
>>> dt = datetime(2007, 4, 1, 15, 30)
>>> format_datetime(dt, locale='en_US')
u'Apr 1, 2007, 3:30:00 PM'
For any pattern requiring the display of the time-zone, the third-party
``pytz`` package is needed to explicitly specify the time-zone:
>>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
... locale='fr_FR')
u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
>>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
... tzinfo=get_timezone('US/Eastern'), locale='en')
u'2007.04.01 AD at 11:30:00 EDT'
:param datetime: the `datetime` object; if `None`, the current date and
time is used
:param format: one of "full", "long", "medium", or "short", or a custom
date/time pattern
:param tzinfo: the timezone to apply to the time for display
:param locale: a `Locale` object or a locale identifier
"""
datetime = _ensure_datetime_tzinfo(_get_datetime(datetime), tzinfo)
locale = Locale.parse(locale)
if format in ('full', 'long', 'medium', 'short'):
return get_datetime_format(format, locale=locale) \
.replace("'", "") \
.replace('{0}', format_time(datetime, format, tzinfo=None,
locale=locale)) \
.replace('{1}', format_date(datetime, format, locale=locale))
else:
return parse_pattern(format).apply(datetime, locale)
示例9: _get_new_datetime
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def _get_new_datetime(self, datetime, relative_mod, time_mod):
"""Build new datetime from relative and time modifiers."""
if relative_mod:
datetime += relative_mod
if time_mod:
return datetime.replace(hour=time_mod.hour, minute=time_mod.minute)
return datetime
示例10: datetime_to_int
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def datetime_to_int(self, datetime):
return int(datetime.replace("T", "").replace(":", ""))
示例11: maintain_thread
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def maintain_thread(self, firstCallResult=None):
''' thread to update token and
register next update event into event loop '''
r = firstCallResult or self._syncTokenFunction()
if not r:
self.core.ioLoop.call_later(
(datetime.replace(datetime.now() + timedelta(days=1),
hour=0, minute=5, second=0) - datetime.now()).seconds,
self.maintain_access_token, None)
else:
self.core.ioLoop.call_later(r['expires_in'] - 30,
self.maintain_access_token, None)
示例12: set_server_list
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def set_server_list(self):
self._serverList = []
serverList, fetchTime = self.core.atStorage.get_server_list()
if fetchTime < time.mktime(datetime.replace(datetime.now(),
hour=0, minute=0, second=0).timetuple()):
r = self._serverIpFn()
if not r:
logger.debug(r)
else:
self._serverList = r.get('ip_list', [])
self.core.atStorage.store_server_list(self._serverList, time.time())
else:
self._serverList = serverList
示例13: filter_request
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def filter_request(self, request):
if self._serverList is None:
t = threading.Thread(target=self.set_server_list)
t.setDaemon = True
t.start()
def clear_server_list():
self._serverList = None
self.core.ioLoop.call_later(
(datetime.replace(datetime.now() + timedelta(days=1),
hour=0, minute=5, second=0) - datetime.now()).seconds,
clear_server_list)
if not self._serverList:
logger.debug('Server list is loading, so ignore verifying once.')
return True
return request.remote_ip in self._serverList
示例14: get_next_timezone_transition
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def get_next_timezone_transition(zone=None, dt=None):
"""Given a timezone it will return a :class:`TimezoneTransition` object
that holds the information about the next timezone transition that's going
to happen. For instance this can be used to detect when the next DST
change is going to happen and how it looks like.
The transition is calculated relative to the given datetime object. The
next transition that follows the date is used. If a transition cannot
be found the return value will be `None`.
Transition information can only be provided for timezones returned by
the :func:`get_timezone` function.
:param zone: the timezone for which the transition should be looked up.
If not provided the local timezone is used.
:param dt: the date after which the next transition should be found.
If not given the current time is assumed.
"""
zone = get_timezone(zone)
if dt is None:
dt = datetime.utcnow()
else:
dt = dt.replace(tzinfo=None)
if not hasattr(zone, '_utc_transition_times'):
raise TypeError('Given timezone does not have UTC transition '
'times. This can happen because the operating '
'system fallback local timezone is used or a '
'custom timezone object')
try:
idx = max(0, bisect_right(zone._utc_transition_times, dt))
old_trans = zone._transition_info[idx - 1]
new_trans = zone._transition_info[idx]
old_tz = zone._tzinfos[old_trans]
new_tz = zone._tzinfos[new_trans]
except (LookupError, ValueError):
return None
return TimezoneTransition(
activates=zone._utc_transition_times[idx],
from_tzinfo=old_tz,
to_tzinfo=new_tz,
reference_date=dt
)
示例15: get_timezone_gmt
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import replace [as 別名]
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
"""Return the timezone associated with the given `datetime` object formatted
as string indicating the offset from GMT.
>>> dt = datetime(2007, 4, 1, 15, 30)
>>> get_timezone_gmt(dt, locale='en')
u'GMT+00:00'
>>> tz = get_timezone('America/Los_Angeles')
>>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
>>> get_timezone_gmt(dt, locale='en')
u'GMT-08:00'
>>> get_timezone_gmt(dt, 'short', locale='en')
u'-0800'
The long format depends on the locale, for example in France the acronym
UTC string is used instead of GMT:
>>> get_timezone_gmt(dt, 'long', locale='fr_FR')
u'UTC-08:00'
.. versionadded:: 0.9
:param datetime: the ``datetime`` object; if `None`, the current date and
time in UTC is used
:param width: either "long" or "short"
:param locale: the `Locale` object, or a locale string
"""
if datetime is None:
datetime = datetime_.utcnow()
elif isinstance(datetime, integer_types):
datetime = datetime_.utcfromtimestamp(datetime).time()
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=UTC)
locale = Locale.parse(locale)
offset = datetime.tzinfo.utcoffset(datetime)
seconds = offset.days * 24 * 60 * 60 + offset.seconds
hours, seconds = divmod(seconds, 3600)
if width == 'short':
pattern = u'%+03d%02d'
else:
pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
return pattern % (hours, seconds // 60)