Python datetime.html() Examples

The following are code examples for showing how to use datetime.html(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: aws-cfn-plex   Author: lordmuffin   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 2
Project: AshsSDK   Author: thehappydinoa   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 3
Project: nmmn   Author: rsnemmen   File: misc.py    (license) View Source Project 6 votes vote down vote up
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 
Example 4
Project: aws-ec2rescue-linux   Author: awslabs   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 5
Project: ac-mediator   Author: AudioCommons   File: views.py    (license) View Source Project 6 votes vote down vote up
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}) 
Example 6
Project: kscore   Author: liuyichen   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 7
Project: jepsen-training-vpc   Author: bloomberg   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 8
Project: jinjabread   Author: Inveracity   File: utils.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 9
Project: jinjabread   Author: Inveracity   File: utils.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 10
Project: AWS-AutoTag   Author: cpollard0   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 11
Project: tf_aws_ecs_instance_draining_on_scale_in   Author: terraform-community-modules   File: compat.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 12
Project: oscars2016   Author: 0x0ece   File: file_cache.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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) 
Example 13
Project: pip-update-requirements   Author: alanhamlett   File: writer.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
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() 
Example 14
Project: code   Author: ActiveState   File: recipe-580725.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 15
Project: v2ex-tornado-2   Author: coderyy   File: filters.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
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/ 
Example 16
Project: v2ex-tornado-2   Author: coderyy   File: filters.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
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 
Example 17
Project: twisted-json-rpc   Author: elston   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 18
Project: GAMADV-XTD   Author: taers232c   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 19
Project: nmmn   Author: rsnemmen   File: misc.py    (license) View Source Project 5 votes vote down vote up
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') 
Example 20
Project: REMAP   Author: REMAPApp   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 21
Project: nanosat-control   Author: ceyzeriat   File: ms.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 22
Project: nanosat-control   Author: ceyzeriat   File: day.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 23
Project: OneClickDTU   Author: satwikkansal   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 24
Project: ac-mediator   Author: AudioCommons   File: views.py    (license) View Source Project 5 votes vote down vote up
def application_monitor(request, pk):
    application = get_object_or_404(ApiClient, pk=pk)
    tvars = {'application': application}
    return render(request, 'developers/application_monitor.html', tvars) 
Example 25
Project: PandasSchema   Author: TMiguelT   File: validation.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 26
Project: PandasSchema   Author: TMiguelT   File: validation.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 27
Project: pipenv   Author: pypa   File: writer.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 28
Project: Chromium_DepotTools   Author: p07r0457   File: git_dates.py    (license) View Source Project 5 votes vote down vote up
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 
Example 29
Project: Full-Footprinting-with-Python   Author: ahmetgurel   File: _3_adjust.py    (license) View Source Project 5 votes vote down vote up
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 
Example 30
Project: alfredToday   Author: jeeftor   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 31
Project: node-gn   Author: Shouqun   File: git_dates.py    (license) View Source Project 5 votes vote down vote up
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 
Example 32
Project: Webradio_v2   Author: Acer54   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 33
Project: GAMADV-X   Author: taers232c   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 34
Project: noobotkit   Author: nazroll   File: timezone.py    (license) View Source Project 5 votes vote down vote up
def dst(self, dt):
        #ISO8601 specifies offsets should be different if DST is required,
        #instead of allowing for a DST to be specified
        # https://docs.python.org/2/library/datetime.html#datetime.tzinfo.dst
        return datetime.timedelta(0) 
Example 35
Project: depot_tools   Author: webrtc-uwp   File: git_dates.py    (license) View Source Project 5 votes vote down vote up
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 
Example 36
Project: share-class   Author: junyiacademy   File: file_cache.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 37
Project: Chorus   Author: DonaldBough   File: timezone.py    (license) View Source Project 5 votes vote down vote up
def dst(self, dt):
        #ISO 8601 specifies offsets should be different if DST is required,
        #instead of allowing for a DST to be specified
        # https://docs.python.org/2/library/datetime.html#datetime.tzinfo.dst
        return datetime.timedelta(0)