def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
python类html()的实例源码
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
def string2year(s):
"""
Converts from a string in the format DDMMYYYY to a python datetime tuple.
>>> string2year('28122014')
returns datetime.datetime(2014, 12, 22, 0, 0).
:param y: a string or list of strings
:returns: a datetime structure (or list) with the date corresponding to the input float or array
Reference: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
"""
import datetime
if numpy.size(s)==1: # if input is a string
date=datetime.datetime.strptime(str(s),'%d%m%Y')
else: # if input is list/array
date=[]
for i, si in enumerate(s):
date.append(datetime.datetime.strptime(str(si),'%d%m%Y'))
return date
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
def get_application_monitor_data(request, pk):
"""
Returns API client usage data to be shown in the monitor page.
This view should return a JSON response with a 'data' field including a list of API usage event.
Each event should include a 'date' field with the timestamp as returned by Pythons Datetime.timestamp() object
(https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp) and with a 'service' property
with the service name (to which a request was forwarded).
"""
#application = get_object_or_404(ApiClient, pk=pk)
fake_data_points = list()
today = datetime.datetime.today()
services = get_available_services()
import random
N_FAKE_POINTS = 1000
DAYS_SPAN = 60
for i in range(0, N_FAKE_POINTS):
fake_data_points.append({
'date': (today - datetime.timedelta(minutes=random.randint(0, 60*24*DAYS_SPAN))).timestamp(),
'service': random.choice(services).name,
})
return JsonResponse({'data': fake_data_points})
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
def gen_mac(prefix='AC:DE:48'):
'''
Generates a MAC address with the defined OUI prefix.
Common prefixes:
- ``00:16:3E`` -- Xen
- ``00:18:51`` -- OpenVZ
- ``00:50:56`` -- VMware (manually generated)
- ``52:54:00`` -- QEMU/KVM
- ``AC:DE:48`` -- PRIVATE
References:
- http://standards.ieee.org/develop/regauth/oui/oui.txt
- https://www.wireshark.org/tools/oui-lookup.html
- https://en.wikipedia.org/wiki/MAC_address
'''
return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix,
random.randint(0, 0xff),
random.randint(0, 0xff),
random.randint(0, 0xff))
def date_format(date=None, format="%Y-%m-%d"):
'''
Converts date into a time-based string
date
any datetime, time string representation...
format
:ref:`strftime<http://docs.python.org/2/library/datetime.html#datetime.datetime.strftime>` format
>>> import datetime
>>> src = datetime.datetime(2002, 12, 25, 12, 00, 00, 00)
>>> date_format(src)
'2002-12-25'
>>> src = '2002/12/25'
>>> date_format(src)
'2002-12-25'
>>> src = 1040814000
>>> date_format(src)
'2002-12-25'
>>> src = '1040814000'
>>> date_format(src)
'2002-12-25'
'''
return date_cast(date).strftime(format)
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
compat.py 文件源码
项目:tf_aws_ecs_instance_draining_on_scale_in
作者: terraform-community-modules
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def total_seconds(delta):
"""
Returns the total seconds in a ``datetime.timedelta``.
Python 2.6 does not have ``timedelta.total_seconds()``, so we have
to calculate this ourselves. On 2.7 or better, we'll take advantage of the
built-in method.
The math was pulled from the ``datetime`` docs
(http://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds).
:param delta: The timedelta object
:type delta: ``datetime.timedelta``
"""
if sys.version_info[:2] != (2, 6):
return delta.total_seconds()
day_in_seconds = delta.days * 24 * 3600.0
micro_in_seconds = delta.microseconds / 10.0**6
return day_in_seconds + delta.seconds + micro_in_seconds
# Checks to see if md5 is available on this system. A given system might not
# have access to it for various reasons, such as FIPS mode being enabled.
def _to_timestamp(date):
try:
return (date - EPOCH).total_seconds()
except AttributeError:
# The following is the equivalent of total_seconds() in Python2.6.
# See also: https://docs.python.org/2/library/datetime.html
delta = date - EPOCH
return ((delta.microseconds + (delta.seconds + delta.days * 24 * 3600)
* 10**6) / 10**6)
def _format_list(v):
return '[{0}]'.format(', '.join(_format_value(obj) for obj in v))
# Formula from:
# https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
# Once support for py26 is dropped, this can be replaced by td.total_seconds()
def set_selection(self, date):
"""Set the selected date."""
if self._selected_date is not None and self._selected_date != date:
self._clear_selection()
self._selected_date = date
self._build_calendar(date.year, date.month) # reconstruct calendar
# see this URL for date format information:
# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
def youku(value):
videos = re.findall('(http://v.youku.com/v_show/id_[a-zA-Z0-9\=]+.html)\s?', value)
logging.error(value)
logging.error(videos)
if (len(videos) > 0):
for video in videos:
video_id = re.findall('http://v.youku.com/v_show/id_([a-zA-Z0-9\=]+).html', video)
value = value.replace('http://v.youku.com/v_show/id_' + video_id[0] + '.html', '<embed src="http://player.youku.com/player.php/sid/' + video_id[0] + '/v.swf" quality="high" width="638" height="420" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"></embed>')
return value
else:
return value
# auto convert tudou.com links to player
# example: http://www.tudou.com/programs/view/ro1Yt1S75bA/
def is_aware(value):
"""
Determines if a given datetime.datetime is aware.
The concept is defined in Python's docs:
http://docs.python.org/library/datetime.html#datetime.tzinfo
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
value.utcoffset() implements the appropriate logic.
"""
return value.utcoffset() is not None
# add from https://github.com/angelbot/geoincentives/blob/7b156fc0d223a1e9376e83651c7c8ad5deaa2b0f/coffin/template/defaultfilters.py
def is_aware(value):
"""
Determines if a given datetime.datetime is aware.
The concept is defined in Python's docs:
http://docs.python.org/library/datetime.html#datetime.tzinfo
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
value.utcoffset() implements the appropriate logic.
"""
return value.utcoffset() is not None
def _to_timestamp(date):
try:
return (date - EPOCH).total_seconds()
except AttributeError:
# The following is the equivalent of total_seconds() in Python2.6.
# See also: https://docs.python.org/2/library/datetime.html
delta = date - EPOCH
return ((delta.microseconds + (delta.seconds + delta.days * 24 * 3600)
* 10**6) / 10**6)
def savepartial(x,y,z,obsx,obsy,obsz,outfile):
"""
Exports data file for partial correlation analysis with cens_tau.f.
cens_tau.f quantifies the correlation between X and Y eliminating the
effect of a third variable Z. I patched the Fortran code available from
http://astrostatistics.psu.edu/statcodes/sc_regression.html.
Method arguments:
x,y,z = arrays with data for partial correlation
obs? = arrays of integers. 1 if there is a genuine measurement
available and 0 if there is only an upper limit i.e. censored data.
In the case of this study, X=Pjet, Y=Lgamma, Z=distance.
The structure of the resulting datafile is:
logPjet detected? logLgamma detected? logDist detected?
where the distance is in Mpc.
Example:
>>> agngrb.exportpartial(all.kp,all.lg,log10(all.d),ones_like(all.kp),ones_like(all.kp),ones_like(all.kp),'par
tialdata.dat')
v1 Sep. 2011
"""
numpy.savetxt(outfile,numpy.transpose((x,obsx,y,obsy,z,obsz)),fmt='%10.4f %i %10.4f %i %10.4f %i')
def _to_timestamp(date):
try:
return (date - EPOCH).total_seconds()
except AttributeError:
# The following is the equivalent of total_seconds() in Python2.6.
# See also: https://docs.python.org/2/library/datetime.html
delta = date - EPOCH
return ((delta.microseconds + (delta.seconds + delta.days * 24 * 3600)
* 10**6) / 10**6)
def strf(self, fmt='%H:%M:%S'):
"""
Returns the formatted string of the time
Args:
* fmt (time format): %H=hours, %M=minutes, %S=seconds,
%f=microseconds. Check:
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
"""
return self._time.strftime(fmt)
def strf(self, fmt='%Y/%m/%d'):
"""
Returns the formatted string of the time
Args:
* fmt (time format): check
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
"""
return self._date.strftime(fmt)
def _to_timestamp(date):
try:
return (date - EPOCH).total_seconds()
except AttributeError:
# The following is the equivalent of total_seconds() in Python2.6.
# See also: https://docs.python.org/2/library/datetime.html
delta = date - EPOCH
return ((delta.microseconds + (delta.seconds + delta.days * 24 * 3600)
* 10**6) / 10**6)
def application_monitor(request, pk):
application = get_object_or_404(ApiClient, pk=pk)
tvars = {'application': application}
return render(request, 'developers/application_monitor.html', tvars)
def __init__(self, pattern, options={}, **kwargs):
"""
:param kwargs: Arguments to pass to Series.str.contains
(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html)
pat is the only required argument
"""
self.pattern = pattern
self.options = options
super().__init__(**kwargs)
def __init__(self, date_format: str, **kwargs):
"""
:param date_format: The date format string to validate the column against. Refer to the date format code
documentation at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior for a full
list of format codes
"""
self.date_format = date_format
super().__init__(**kwargs)
def _format_list(v):
return '[{0}]'.format(', '.join(_format_value(obj) for obj in v))
# Formula from:
# https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
# Once support for py26 is dropped, this can be replaced by td.total_seconds()
def datetime_string(dt):
"""Converts a tz-aware datetime.datetime into a string in git format."""
return dt.strftime('%Y-%m-%d %H:%M:%S %z')
# Adapted from: https://docs.python.org/2/library/datetime.html#tzinfo-objects
def __init__(self, data):
self.name = data['domain_name'][0].strip().lower()
self.registrar = data['registrar'][0].strip()
self.creation_date = str_to_date(data['creation_date'][0])
self.expiration_date = str_to_date(data['expiration_date'][0])
self.last_updated = str_to_date(data['updated_date'][0])
#----------------------------------
# name_servers
tmp = []
for x in data['name_servers']:
if isinstance(x, str): tmp.append(x)
else:
for y in x: tmp.append(y)
self.name_servers = set()
for x in tmp:
x = x.strip(' .')
if x:
if ' ' in x:
x, _ = x.split(' ', 1)
x = x.strip(' .')
self.name_servers.add(x.lower())
#----------------------------------
# http://docs.python.org/library/datetime.html#strftime-strptime-behavior
def _to_timestamp(date):
try:
return (date - EPOCH).total_seconds()
except AttributeError:
# The following is the equivalent of total_seconds() in Python2.6.
# See also: https://docs.python.org/2/library/datetime.html
delta = date - EPOCH
return ((delta.microseconds + (delta.seconds + delta.days * 24 * 3600)
* 10**6) / 10**6)