Python datetime.utcnow() Examples

The following are code examples for showing how to use datetime.utcnow(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: deep-nn-car   Author: scope-lab-vu   File: IO.py    MIT License 6 votes vote down vote up
def zeroDetectionHandler(signum,frame):
    global start_timer,maxElapse,speed
    global speeds,timestamps
    elapsed = time.time() - start_timer
    if (elapsed > maxElapse):
        speed = 0
        speeds.append(speed)
        timestamps.append(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    #start_timer = time.time()
    signal.signal(signal.SIGALRM,zeroDetectionHandler)
    signal.alarm(maxElapse)


# init()
# Summary: Initializes GPIO
# Parameter: freq   => frequency of PWM signal
#            dcAcc  => duty cycle for acceleration at idle 
Example 2
Project: bot   Author: python-discord   File: time.py    MIT License 6 votes vote down vote up
def format_infraction_with_duration(
    expiry: Optional[str],
    date_from: Optional[datetime.datetime] = None,
    max_units: int = 2
) -> Optional[str]:
    """
    Format an infraction timestamp to a more readable ISO 8601 format WITH the duration.

    Returns a human-readable version of the duration between datetime.utcnow() and an expiry.
    Unlike `humanize_delta`, this function will force the `precision` to be `seconds` by not passing it.
    `max_units` specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
    By default, max_units is 2.
    """
    if not expiry:
        return None

    date_from = date_from or datetime.datetime.utcnow()
    date_to = dateutil.parser.isoparse(expiry).replace(tzinfo=None, microsecond=0)

    expiry_formatted = format_infraction(expiry)

    duration = humanize_delta(relativedelta(date_to, date_from), max_units=max_units)
    duration_formatted = f" ({duration})" if duration else ''

    return f"{expiry_formatted}{duration_formatted}" 
Example 3
Project: bot   Author: python-discord   File: time.py    MIT License 6 votes vote down vote up
def until_expiration(
    expiry: Optional[str],
    now: Optional[datetime.datetime] = None,
    max_units: int = 2
) -> Optional[str]:
    """
    Get the remaining time until infraction's expiration, in a human-readable version of the relativedelta.

    Returns a human-readable version of the remaining duration between datetime.utcnow() and an expiry.
    Unlike `humanize_delta`, this function will force the `precision` to be `seconds` by not passing it.
    `max_units` specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
    By default, max_units is 2.
    """
    if not expiry:
        return None

    now = now or datetime.datetime.utcnow()
    since = dateutil.parser.isoparse(expiry).replace(tzinfo=None, microsecond=0)

    if since < now:
        return None

    return humanize_delta(relativedelta(since, now), max_units=max_units) 
Example 4
Project: SparseSC   Author: microsoft   File: azure_batch_client.py    MIT License 6 votes vote down vote up
def build_output_sas_url(config, _blob_client):
    """
    build a sas token for the output container
    """

    sas_token = _blob_client.generate_container_shared_access_signature(
        config.CONTAINER_NAME,
        ContainerPermissions.READ
        + ContainerPermissions.WRITE
        + ContainerPermissions.DELETE
        + ContainerPermissions.LIST,
        datetime.datetime.utcnow() + datetime.timedelta(hours=config.STORAGE_ACCESS_DURATION_HRS),
        start=datetime.datetime.utcnow(),
    )

    _sas_url = "https://{}.blob.core.windows.net/{}?{}".format(
        config.STORAGE_ACCOUNT_NAME, config.CONTAINER_NAME, sas_token
    )
    return _sas_url 
Example 5
Project: Zarena   Author: Margeeks   File: info.py    MIT License 6 votes vote down vote up
def get_bot_uptime(self, *, brief=False):
        now = datetime.datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        if not brief:
            if days:
                fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
            else:
                fmt = '{h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h}h {m}m {s}s'
            if days:
                fmt = '{d}d ' + fmt

        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 6
Project: Zarena   Author: Margeeks   File: info.py    MIT License 6 votes vote down vote up
def get_uptime(self, *, brief=False):
        # bot.launch_time = datetime.utcnow()
        delta_uptime = datetime.utcnow() - self.launch_time
        (hours, remainder) = divmod(int(delta_uptime.total_seconds()), 3600)
        (minutes, seconds) = divmod(remainder, 60)
        (days, hours) = divmod(hours, 24)
        if (not brief):
            if days:
                fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
            else:
                fmt = '{h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h}h {m}m {s}s'
            if days:
                fmt = '{d}d ' + fmt
        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 7
Project: chan_feed   Author: simon987   File: run.py    GNU General Public License v3.0 6 votes vote down vote up
def publish(item, board, helper, channel, web):
    post_process(item, board, helper, web)

    item_type = helper.item_type(item)
    routing_key = "%s.%s.%s" % (chan, item_type, board)

    _publish_buffered([(channel, routing_key, item)])

    if MONITORING:
        distance = datetime.utcnow() - datetime.utcfromtimestamp(helper.item_mtime(item))
        influxdb.log([{
            "measurement": chan,
            "time": str(datetime.utcnow()),
            "tags": {
                "board": board
            },
            "fields": {
                "distance": distance.total_seconds()
            }
        }]) 
Example 8
Project: cloud-opensource-python   Author: GoogleCloudPlatform   File: test_pip_checker.py    Apache License 2.0 6 votes vote down vote up
def exec_run(self, cmd, stdout=True, stderr=True):
        from datetime import datetime

        _stdout = subprocess.PIPE if stdout else None
        _stderr = subprocess.PIPE if stderr else None
        result = subprocess.run(
            cmd, stderr=_stderr, stdout=_stdout)

        output = result.stdout if stdout else b''
        output += result.stderr if stderr else b''

        current_time = timestamp_to_seconds(
            datetime.utcnow().isoformat() + 'Z')
        duration = current_time - self.start_time

        if duration > pip_checker.TIME_OUT:
            result.returncode = 137
            output = b''

        return result.returncode, output 
Example 9
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.assertIs(now.tzinfo, weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 11
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_utcnow(self):
        meth = self.theclass.utcnow
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword; for whatever reason,
        # utcnow() doesn't accept a tzinfo argument.
        off42 = FixedOffset(42, "42")
        self.assertRaises(TypeError, meth, off42)
        self.assertRaises(TypeError, meth, tzinfo=off42) 
Example 12
Project: deep-nn-car   Author: scope-lab-vu   File: Pin_Controller.py    MIT License 5 votes vote down vote up
def calculate_elapse(channel):				# callback function
    global start_timer, elapse,speed
    global timestamps,speeds,elapses
    elapse = time.time() - start_timer		# elapse for every 1 complete rotation made!
    if elapse != 0:							# to avoid DivisionByZero error
        rpm = (1 / elapse)*60 
        circumference = math.pi * diameter
        speed = (rpm*circumference/60)/1000
        speeds.append(speed)
        elapses.append(elapse)
        timestamps.append(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    print(speed)
    start_timer = time.time()				# let current time equals to start_timer

#getSpeed() 
Example 13
Project: deep-nn-car   Author: scope-lab-vu   File: IO.py    MIT License 5 votes vote down vote up
def calculate_elapse(channel):				# callback function
    global start_timer, elapse,speed
    global timestamps,speeds
    elapse = time.time() - start_timer		# elapse for every 1 complete rotation made!
    if elapse != 0:							# to avoid DivisionByZero error
        rpm = (1 / elapse)*60 
        circumference = math.pi * diameter
        speed = (rpm*circumference/60)/1000
        speeds.append(speed)
        timestamps.append(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    start_timer = time.time()				# let current time equals to start_timer

# zeroDetectionHandler()
# description: Detects when speed = 0 m/s 
Example 14
Project: bloop   Author: numberoverzero   File: types.py    MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        dt = value.astimezone(tz=datetime.timezone.utc)
        return dt.strftime(FIXED_ISO8601_FORMAT) 
Example 15
Project: bloop   Author: numberoverzero   File: types.py    MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        value = value.timestamp()
        return super().dynamo_dump(value, context=context, **kwargs) 
Example 16
Project: bot   Author: python-discord   File: time.py    MIT License 5 votes vote down vote up
def time_since(past_datetime: datetime.datetime, precision: str = "seconds", max_units: int = 6) -> str:
    """
    Takes a datetime and returns a human-readable string that describes how long ago that datetime was.

    precision specifies the smallest unit of time to include (e.g. "seconds", "minutes").
    max_units specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
    """
    now = datetime.datetime.utcnow()
    delta = abs(relativedelta(now, past_datetime))

    humanized = humanize_delta(delta, precision, max_units)

    return f"{humanized} ago" 
Example 17
Project: bot   Author: python-discord   File: time.py    MIT License 5 votes vote down vote up
def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
    """
    Wait until a given time.

    :param time: A datetime.datetime object to wait until.
    :param start: The start from which to calculate the waiting duration. Defaults to UTC time.
    """
    delay = time - (start or datetime.datetime.utcnow())
    delay_seconds = delay.total_seconds()

    # Incorporate a small delay so we don't rapid-fire the event due to time precision errors
    if delay_seconds > 1.0:
        await asyncio.sleep(delay_seconds) 
Example 18
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log1():
    ndt = datetime.now()
    for data in msg_dict1:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict1[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict1[msg_id] 
Example 19
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log():
    ndt = datetime.now()
    for data in msg_dict:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict[msg_id] 
Example 20
Project: mist.api   Author: mistio   File: base.py    Apache License 2.0 5 votes vote down vote up
def list_cached_machines(self, timedelta=datetime.timedelta(days=1)):
        """Return list of machines from database

        Only returns machines that existed last time we check and we've seen
        during the last `timedelta`.

        """
        from mist.api.machines.models import Machine
        return Machine.objects(
            cloud=self.cloud,
            missing_since=None,
            last_seen__gt=datetime.datetime.utcnow() - timedelta,
        ) 
Example 21
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance) 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.assertIs(now.tzinfo, weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 23
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_tzinfo_utcnow(self):
        meth = self.theclass.utcnow
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword; for whatever reason,
        # utcnow() doesn't accept a tzinfo argument.
        off42 = FixedOffset(42, "42")
        self.assertRaises(TypeError, meth, off42)
        self.assertRaises(TypeError, meth, tzinfo=off42) 
Example 24
Project: SparseSC   Author: microsoft   File: azure_batch_client.py    MIT License 5 votes vote down vote up
def upload_file_to_container(block_blob_client, container_name, file_path, duration_hours=24):
    """
    Uploads a local file to an Azure Blob storage container.

    :param block_blob_client: A blob service client.
    :type block_blob_client: `azure.storage.blob.BlockBlobService`
    :param str container_name: The name of the Azure Blob storage container.
    :param str file_path: The local path to the file.
    :rtype: `azure.batch.models.ResourceFile`
    :return: A ResourceFile initialized with a SAS URL appropriate for Batch
    tasks.
    """
    blob_name = os.path.basename(file_path)

    print("Uploading file {} to container [{}]...".format(file_path, container_name))

    block_blob_client.create_blob_from_path(container_name, blob_name, file_path)

    sas_token = block_blob_client.generate_blob_shared_access_signature(
        container_name,
        blob_name,
        permission=azureblob.BlobPermissions.READ,
        expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=duration_hours),
    )

    sas_url = block_blob_client.make_blob_url(
        container_name, blob_name, sas_token=sas_token
    )

    return models.ResourceFile(http_url=sas_url, file_path=_CONTAINER_INPUT_FILE) 
Example 25
Project: annotatron   Author: Sentimentron   File: storage.py    MIT License 5 votes vote down vote up
def _save(self, name, content):
        content.seek(0, 0)
        buffer = content.read()
        blob = Blob.objects.create(external_id=name, blob=buffer, inserted_date=datetime.utcnow())
        blob.save()
        return name 
Example 26
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    MIT License 5 votes vote down vote up
def test_class_ops(self):
        _skip_if_no_pytz()
        import pytz

        def compare(x,y):
            self.assertEqual(int(Timestamp(x).value/1e9), int(Timestamp(y).value/1e9))

        compare(Timestamp.now(),datetime.now())
        compare(Timestamp.now('UTC'),datetime.now(pytz.timezone('UTC')))
        compare(Timestamp.utcnow(),datetime.utcnow())
        compare(Timestamp.today(),datetime.today()) 
Example 27
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.assertLessEqual(abs(from_timestamp - from_now), tolerance) 
Example 28
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.assertIs(now.tzinfo, weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 29
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_tzinfo_utcnow(self):
        meth = self.theclass.utcnow
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword; for whatever reason,
        # utcnow() doesn't accept a tzinfo argument.
        off42 = FixedOffset(42, "42")
        self.assertRaises(TypeError, meth, off42)
        self.assertRaises(TypeError, meth, tzinfo=off42) 
Example 30
Project: sparknotebook   Author: eleflow   File: spark_ec2.py    Apache License 2.0 5 votes vote down vote up
def find_best_price(conn,instance,zone, factor):
  last_hour_zone = get_spot_price(conn,zone,datetime.utcnow()-timedelta(hours=1),instance)
  average_price_last_hour = sum(i.price for i in last_hour_zone)/float(len(last_hour_zone))
  return average_price_last_hour*factor 
Example 31
Project: sparknotebook   Author: eleflow   File: spark_ec2.py    Apache License 2.0 5 votes vote down vote up
def get_spot_price(conn,zone,start_date_hour,instance):
    return conn.get_spot_price_history(start_time=start_date_hour.strftime("%Y-%m-%dT%H:%M:%SZ"),end_time = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),instance_type=instance , product_description="Linux/UNIX",availability_zone=zone) 
Example 32
Project: rome   Author: BeyondTheClouds   File: utils.py    MIT License 5 votes vote down vote up
def soft_delete(self, session):
        """Mark this object as deleted."""
        self.deleted = self.id
        self.deleted_at = timeutils.utcnow()
        self.save(session=session) 
Example 33
Project: Zarena   Author: Margeeks   File: info.py    MIT License 5 votes vote down vote up
def __init__(self, bot):
        self.bot = bot
        self.config = default.get("config.json")
        self.process = psutil.Process(os.getpid())
        self.launch_time = datetime.utcnow()
        bot.remove_command('help') 
Example 34
Project: EvapoTranspiration   Author: linuxha   File: weatherCustom.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def getTZoneOffset(tz):
    if tz:
        try:
            tnow = pytz.utc.localize(datetime.utcnow())
            tdelta = tnow.astimezone(pytz.timezone(tz)).utcoffset()
            return {'t'  : tdelta.days * 96 + tdelta.seconds / 900 + 48,
                    'gmt': (86400 * tdelta.days + tdelta.seconds) / 3600}
        except:
            return {'t': None, 'gmt': None}
        #
    #
#

# Get all data for the location this should only be called once, several functions below will handle the data 
Example 35
Project: slackn   Author: bcicen   File: __init__.py    MIT License 5 votes vote down vote up
def _stats(self, notify_args):
        """ Record attributes of the notification to Redis """
        now = str(datetime.utcnow())
        self._increment('notifications', 1)
        self._increment('host:' + notify_args['hostname'], 1)
        self.redis.hset(stats_key, 'last_notification', now) 
Example 36
Project: Protect4   Author: Aditmadzs   File: adit4.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log():
    ndt = datetime.now()
    for data in msg_dict:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict[msg_id] 
Example 37
Project: pipeline-microservice   Author: MonashBioinformaticsPlatform   File: jwt_helpers.py    Apache License 2.0 5 votes vote down vote up
def create_object_access_jwt(obj, ttl=None):
    """
    Create a JWT token representing an access claim to any Django object,
    discovered by id and ContentType.

    :param obj: The token will be authorized to modify this object. Requires
                an id attribute and a registered ContentType.
    :type obj: django.db.models.Model
    :param ttl: The length of time the key will be valid for. Defaults to
                JWT_EXPIRATION_DELTA from settings.
    :type ttl: datetime.timedelta
    :return: The signed JWT token.
    :rtype: str
    """
    if not ttl:
        ttl = settings.JWT_AUTH['JWT_EXPIRATION_DELTA']

    now = datetime.utcnow()
    expiry = now + ttl
    content_type = ContentType.objects.get_for_model(obj).model
    token = jwt.encode({'id': obj.id,
                        'content_type': content_type,
                        # The 'permission' field is currently unused, but
                        # could be used to determine access type (eg read/write)
                        'permission': 'rw',
                        'exp': expiry,
                        'iat': now,
                        'nbf': now,
                        # The 'jti' field is currently a placeholder, unused.
                        # It is a unique identifier for the token.
                        # We would use it if we wanted to revoke keys prior
                        # to expiration (eg upon job completion). This would
                        # require storing every JWT (+jti) issued (or
                        # associating the jti with the Job model, eg via a
                        # GenericForeignKey), and doing a database lookup for
                        # revoked keys when we verify for decode incoming JWTs.
                        'jti': uuid.uuid4().hex,
                        },
                       settings.JWT_AUTH['JWT_SECRET_KEY'],
                       settings.JWT_AUTH['JWT_ALGORITHM'])
    return token 
Example 38
Project: magdalena   Author: KaiRo-at   File: datautils.py    Mozilla Public License 2.0 5 votes vote down vote up
def beforeTodayString(days = 0, weeks = 0):
    from datetime import datetime, timedelta
    return (datetime.utcnow() - timedelta(days=days, weeks=weeks)).strftime('%Y-%m-%d') 
Example 39
Project: geofire-python   Author: ininex   File: test__gax.py    MIT License 5 votes vote down vote up
def _make_timestamp():
        from datetime import datetime
        from gcloud._helpers import UTC
        from gcloud._helpers import _datetime_to_pb_timestamp
        NOW = datetime.utcnow().replace(tzinfo=UTC)
        return _datetime_to_pb_timestamp(NOW) 
Example 40
Project: geofire-python   Author: ininex   File: test_entries.py    MIT License 5 votes vote down vote up
def test_from_api_repr_w_loggers_w_logger_match(self):
        from datetime import datetime
        from gcloud._helpers import UTC
        client = _Client(self.PROJECT)
        PAYLOAD = 'PAYLOAD'
        IID = 'IID'
        NOW = datetime.utcnow().replace(tzinfo=UTC)
        TIMESTAMP = _datetime_to_rfc3339_w_nanos(NOW)
        LOG_NAME = 'projects/%s/logs/%s' % (self.PROJECT, self.LOGGER_NAME)
        LABELS = {'foo': 'bar', 'baz': 'qux'}
        API_REPR = {
            'dummyPayload': PAYLOAD,
            'logName': LOG_NAME,
            'insertId': IID,
            'timestamp': TIMESTAMP,
            'labels': LABELS,
        }
        LOGGER = object()
        loggers = {LOG_NAME: LOGGER}
        klass = self._getTargetClass()
        entry = klass.from_api_repr(API_REPR, client, loggers=loggers)
        self.assertEqual(entry.payload, PAYLOAD)
        self.assertEqual(entry.insert_id, IID)
        self.assertEqual(entry.timestamp, NOW)
        self.assertEqual(entry.labels, LABELS)
        self.assertTrue(entry.logger is LOGGER) 
Example 41
Project: invader   Author: entynetproject   File: helpers.py    MIT License 5 votes vote down vote up
def utc_to_local(utc):
    """
    Converts a datetime object in UTC to local time
    """

    offset = datetime.now() - datetime.utcnow()
    return (utc + offset).strftime("%Y-%m-%d %H:%M:%S") 
Example 42
Project: Aditmadzs2   Author: Aditmadzs   File: adit.py    GNU General Public License v3.0 5 votes vote down vote up
def delete_log():
    ndt = datetime.now()
    for data in msg_dict:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict[msg_id] 
Example 43
Project: virtual-kubelet-web-mock-python   Author: stuartleeks   File: app.py    MIT License 5 votes vote down vote up
def getutcnow():
    return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') 
Example 44
Project: zeit.cms   Author: ZeitOnline   File: testing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def now(cls, tz=None):
        if tz is not None:
            if cls.frozen.tzinfo is None:
                # https://docs.python.org/2/library/datetime.html says,
                # the result is equivalent to tz.fromutc(
                #   datetime.utcnow().replace(tzinfo=tz)).
                return tz.fromutc(cls.frozen.replace(tzinfo=tz))
            else:
                return cls.frozen.astimezone(tz)
        return cls.frozen 
Example 45
Project: zeit.cms   Author: ZeitOnline   File: testing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clock(dt=None):
    if dt is None:
        dt = original.utcnow()
    with mock.patch('datetime.datetime', Freeze):
        Freeze.freeze(dt)
        yield Freeze 
Example 46
Project: OGN-Flight-Logger_V2   Author: tobiz   File: flogger_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def is_dst(zonename):
    # Determine if in daylight
    tz = pytz.timezone(zonename)
    now = pytz.utc.localize(datetime.utcnow())
    return now.astimezone(tz).dst() != timedelta(0) 
Example 47
Project: OGN-Flight-Logger_V2   Author: tobiz   File: flogger.py    GNU General Public License v3.0 5 votes vote down vote up
def is_dst(zonename):
    # Determine if in daylight
    tz = pytz.timezone(zonename)
    now = pytz.utc.localize(datetime.utcnow())
    return now.astimezone(tz).dst() != timedelta(0) 
Example 48
Project: Flask-P2P   Author: chalasr   File: app.py    MIT License 5 votes vote down vote up
def __init__(self, id, username=None):
        self.id = id
        self.username = username
        self.connected_at = datetime.utcnow()
        self.rooms = []
        self.messages = Queue() 
Example 49
Project: EpicDice   Author: casinosteem   File: dice_program.py    MIT License 5 votes vote down vote up
def getUnix():
    d = datetime.utcnow()
    unixtime = calendar.timegm(d.utctimetuple())
    return unixtime 
Example 50
Project: Hot   Author: dsolimando   File: test_datetime.py    GNU General Public License v3.0 5 votes vote down vote up
def test_utcnow(self):
        import time

        # Call it a success if utcnow() and utcfromtimestamp() are within
        # a second of each other.
        tolerance = timedelta(seconds=1)
        for dummy in range(3):
            from_now = self.theclass.utcnow()
            from_timestamp = self.theclass.utcfromtimestamp(time.time())
            if abs(from_timestamp - from_now) <= tolerance:
                break
            # Else try again a few times.
        self.failUnless(abs(from_timestamp - from_now) <= tolerance) 
Example 51
Project: Hot   Author: dsolimando   File: test_datetime.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.failUnless(another.tzinfo is again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.failUnless(now.tzinfo is weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 52
Project: Hot   Author: dsolimando   File: test_datetime.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tzinfo_utcnow(self):
        meth = self.theclass.utcnow
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword; for whatever reason,
        # utcnow() doesn't accept a tzinfo argument.
        off42 = FixedOffset(42, "42")
        self.assertRaises(TypeError, meth, off42)
        self.assertRaises(TypeError, meth, tzinfo=off42) 
Example 53
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow() 
Example 54
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def time_time():
  """Returns the equivalent of time.time() as mocked if applicable."""
  return (utcnow() - EPOCH).total_seconds() 
Example 55
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def milliseconds_since_epoch(now):
  """Returns the number of milliseconds since unix epoch as an int."""
  now = now or utcnow()
  return int(round((now - EPOCH).total_seconds() * 1000.)) 
Example 56
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow() 
Example 57
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def time_time():
  """Returns the equivalent of time.time() as mocked if applicable."""
  return (utcnow() - EPOCH).total_seconds() 
Example 58
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow() 
Example 59
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def time_time():
  """Returns the equivalent of time.time() as mocked if applicable."""
  return (utcnow() - EPOCH).total_seconds() 
Example 60
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def milliseconds_since_epoch(now):
  """Returns the number of milliseconds since unix epoch as an int."""
  now = now or utcnow()
  return int(round((now - EPOCH).total_seconds() * 1000.)) 
Example 61
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow() 
Example 62
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def time_time():
  """Returns the equivalent of time.time() as mocked if applicable."""
  return (utcnow() - EPOCH).total_seconds() 
Example 63
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow() 
Example 64
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def time_time():
  """Returns the equivalent of time.time() as mocked if applicable."""
  return (utcnow() - EPOCH).total_seconds() 
Example 65
Project: luci-py   Author: luci   File: utils.py    Apache License 2.0 5 votes vote down vote up
def milliseconds_since_epoch(now):
  """Returns the number of milliseconds since unix epoch as an int."""
  now = now or utcnow()
  return int(round((now - EPOCH).total_seconds() * 1000.)) 
Example 66
Project: prox-server   Author: mozilla-mobile   File: request_handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def writeSearchRecord(lat, lng, key=None):
    record = representation.geoRecordFromCoord(lat, lng)
    from datetime import datetime
    import time
    now = datetime.utcnow()

    record["timestamp"] = now.isoformat()
    record["time"] = time.time()
    db().child(searchesTable).update({ record["g"]: record }) 
Example 67
Project: sgx-kms   Author: cloud-security-research   File: dogtag.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, conf=CONF):
        """Constructor - create the cert clients."""
        connection = create_connection(conf, 'ca')
        self.certclient = pki.cert.CertClient(connection)
        self.simple_cmc_profile = conf.dogtag_plugin.simple_cmc_profile
        self.auto_approved_profiles = conf.dogtag_plugin.auto_approved_profiles

        self.working_dir = conf.dogtag_plugin.plugin_working_dir
        if not os.path.isdir(self.working_dir):
            os.mkdir(self.working_dir)

        self._expiration = None
        self._expiration_delta = conf.dogtag_plugin.ca_expiration_time
        self._expiration_data_path = os.path.join(self.working_dir,
                                                  "expiration_data.txt")

        self._host_aid_path = os.path.join(self.working_dir, "host_aid.txt")
        self._host_aid = None

        if not os.path.isfile(self._expiration_data_path):
            self.expiration = datetime.datetime.utcnow()

        global subcas_available
        subcas_available = self._are_subcas_enabled_on_backend(connection)
        if subcas_available:
            self.authority_client = authority.AuthorityClient(connection)
            if not os.path.isfile(self._host_aid_path):
                self.host_aid = self.get_host_aid() 
Example 68
Project: sgx-kms   Author: cloud-security-research   File: dogtag.py    Apache License 2.0 5 votes vote down vote up
def expiration(self):
        if self._expiration is None:
            try:
                with open(self._expiration_data_path) as expiration_fh:
                    self._expiration = datetime.datetime.strptime(
                        expiration_fh.read(),
                        "%Y-%m-%d %H:%M:%S.%f"
                    )
            except (ValueError, TypeError):
                LOG.warning(u._LI("Invalid data read from expiration file"))
                self.expiration = datetime.utcnow()
        return self._expiration 
Example 69
Project: sgx-kms   Author: cloud-security-research   File: dogtag.py    Apache License 2.0 5 votes vote down vote up
def get_ca_info(self):
        if not subcas_available:
            return super(DogtagCAPlugin, self).get_ca_info()

        self.expiration = (datetime.datetime.utcnow() + datetime.timedelta(
            days=int(self._expiration_delta)))

        ret = {}
        cas = self.authority_client.list_cas()
        for ca_data in cas.ca_list:
            if not ca_data.enabled:
                continue

            cert = self.authority_client.get_cert(ca_data.aid, "PEM")
            chain = self.authority_client.get_chain(ca_data.aid, "PEM")
            ca_info = {
                cm.INFO_NAME: ca_data.description,
                cm.INFO_CA_SIGNING_CERT: cert,
                cm.INFO_INTERMEDIATES: chain,
                cm.INFO_EXPIRATION: self.expiration.isoformat()
            }

            # handle the migration case.  The top level CA should continue
            # to work as before

            if ca_data.is_host_authority:
                ret[self.get_default_ca_name()] = ca_info
                self.host_aid = ca_data.aid
            else:
                ret[ca_data.aid] = ca_info

        return ret 
Example 70
Project: cloud-opensource-python   Author: GoogleCloudPlatform   File: test_pip_checker.py    Apache License 2.0 5 votes vote down vote up
def run(self,
            base_image,
            command,
            detach=True,
            remove=False,
            auto_remove=False):
        from datetime import datetime

        self.start_time = timestamp_to_seconds(
            datetime.utcnow().isoformat() + 'Z')
        return self 
Example 71
Project: deep-nn-car   Author: scope-lab-vu   File: Server.py    MIT License 4 votes vote down vote up
def dataCollectionDriving(sock,csvfile):
    global speed
    # initialize function variables
    connection = 0
    timestamps=[]
    accDCs = []
    steerDCs = []
    while True:   
        try:
            sock.settimeout(3)
            connection, client_address = sock.accept()
            data = connection.recv(20)
        except sock.timeout:
            print('Connection timed out')
            cleanup(sock,connection)
            break
        dc = make_tuple(data.decode())
        # if a STOP signal is sent, data collection is terminated
        if (data.decode() == "(3,)"):
            message = "Data collection terminated"
            message = message.encode()
            connection.sendall(message)
            break
        # if other special signal is sent, send signal back
        if (len(dc)==1):
            connection.sendall(data)
            continue
        # append timestamp, duty cycle for acceleration, and duty cycle for steering
        timestamps.append(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
        accDCs.append(dc[0])
        steerDCs.append(dc[1])
        # decode client data and change pin values
        data_decoded = data.decode()
        changePins(data_decoded)
        # acknowledge client
        speed = getSpeed()
        speed = float("{0:.2f}".format(speed))
        speed = str(speed)
        connection.sendall(speed.encode())
    # write to .csv and close
    writer=csv.writer(csvfile)
    writer.writerow(timestamps)
    writer.writerow(accDCs)
    writer.writerow(steerDCs)
    csvfile.close()    
    # cleans up processes)
    print('Cleaning up')
    cleanup(sock,connection)

# PWM controller for autonomousDriving Mode
# Waits until a STOP signal ('B') is sent from client
# otherwise used CNN model to generate steering
# and steering control values
# params: sock => socket connection
#         p12 => GPIO acceleration
#         p27 => GPIO steering 
Example 72
Project: mist.api   Author: mistio   File: base.py    Apache License 2.0 4 votes vote down vote up
def _decide_machine_cost(machine, tags=None, cost=(0, 0)):
    """Decide what the monthly and hourly machine cost is

    Params:
    machine:    Machine model instance
    tags:       Optional machine tags dict, if not provided it will be queried.
    cost:       Optional two-tuple of hourly/monthly cost, such as that
                returned by cloud provider.

    Any cost-specific tags take precedence.
    """

    def parse_num(num):
        try:
            return float(num or 0)
        except (ValueError, TypeError):
            log.warning("Can't parse %r as float.", num)
            return 0

    now = datetime.datetime.utcnow()
    month_days = calendar.monthrange(now.year, now.month)[1]

    # Get machine tags from db
    tags = tags or {tag.key: tag.value for tag in Tag.objects(
        resource_id=machine.id, resource_type='machine'
    )}

    try:
        cph = parse_num(tags.get('cost_per_hour'))
        cpm = parse_num(tags.get('cost_per_month'))
        if not (cph or cpm) or cph > 100 or cpm > 100 * 24 * 31:
            log.debug("Invalid cost tags for machine %s", machine)
            cph, cpm = list(map(parse_num, cost))
        if not cph:
            cph = float(cpm) / month_days / 24
        elif not cpm:
            cpm = cph * 24 * month_days
    except Exception:
        log.exception("Error while deciding cost for machine %s", machine)

    machine.cost.hourly = cph
    machine.cost.monthly = cpm 
Example 73
Project: python-flask-restful-api   Author: akashtalole   File: scheduled_jobs.py    MIT License 4 votes vote down vote up
def send_event_fee_notification():
    from app import current_app as app
    with app.app_context():
        events = Event.query.filter_by(deleted_at=None, state='published').all()
        for event in events:
            latest_invoice = EventInvoice.query.filter_by(
                event_id=event.id).order_by(EventInvoice.created_at.desc()).first()

            if latest_invoice:
                orders = Order.query \
                    .filter_by(event_id=event.id) \
                    .filter_by(status='completed') \
                    .filter(Order.completed_at > latest_invoice.created_at).all()
            else:
                orders = Order.query.filter_by(
                    event_id=event.id).filter_by(status='completed').all()

            fee_total = 0
            for order in orders:
                for order_ticket in order.tickets:
                    ticket = safe_query(db, Ticket, 'id', order_ticket.ticket_id, 'ticket_id')
                    if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0:
                        fee = ticket.price * (get_fee(order.event.payment_currency) / 100.0)
                        fee_total += fee

            if fee_total > 0:
                owner = get_user_event_roles_by_role_name(event.id, 'owner').first()
                new_invoice = EventInvoice(
                    amount=fee_total, event_id=event.id, user_id=owner.user.id)

                if event.discount_code_id and event.discount_code:
                    r = relativedelta(datetime.utcnow(), event.created_at)
                    if r <= event.discount_code.valid_till:
                        new_invoice.amount = fee_total - \
                            (fee_total * (event.discount_code.value / 100.0))
                        new_invoice.discount_code_id = event.discount_code_id

                save_to_db(new_invoice)
                prev_month = monthdelta(new_invoice.created_at, 1).strftime(
                    "%b %Y")  # Displayed as Aug 2016
                app_name = get_settings()['app_name']
                frontend_url = get_settings()['frontend_url']
                link = '{}/invoices/{}'.format(frontend_url, new_invoice.identifier)
                send_email_for_monthly_fee_payment(new_invoice.user.email,
                                                   event.name,
                                                   prev_month,
                                                   new_invoice.amount,
                                                   app_name,
                                                   link)
                send_notif_monthly_fee_payment(new_invoice.user,
                                               event.name,
                                               prev_month,
                                               new_invoice.amount,
                                               app_name,
                                               link,
                                               new_invoice.event_id) 
Example 74
Project: website   Author: jazzband-roadies   File: content.py    MIT License 4 votes vote down vote up
def news_feed():
    feed = FeedGenerator()
    feed.id("https://jazzband.co/news/feed")
    feed.link(href="https://jazzband.co/", rel="alternate")
    feed.title("Jazzband News Feed")
    feed.subtitle("We are all part of this.")
    feed.link(href=full_url(request.url), rel="self")

    # the list of updates of all news for setting the feed's updated value
    updates = []

    for page in news_pages:
        if page.path == "index":
            continue

        # make the datetime timezone aware if needed
        published = page.meta.get("published", None)
        if published and published.tzinfo is None:
            published = pytz.utc.localize(published)
        updated = page.meta.get("updated", published)
        if updated:
            if updated.tzinfo is None:
                updated = pytz.utc.localize(updated)
            updates.append(updated)

        summary = page.meta.get("summary", None)
        author = page.meta.get("author", None)
        author_link = page.meta.get("author_link", None)
        url = full_url(url_for("content.news", path=page.path))

        entry = feed.add_entry()
        entry.id(url)
        entry.title(page.meta["title"])
        entry.summary(summary)
        entry.content(content=str(page.html), type="html")

        if author is not None:
            author = {"name": author}
            if author_link is not None:
                author["uri"] = author_link
            entry.author(author)

        entry.link(href=url)
        entry.updated(updated)
        entry.published(published)

    sorted_updates = sorted(updates)
    feed.updated(sorted_updates and sorted_updates[-1] or datetime.utcnow())

    return Response(feed.atom_str(pretty=True), mimetype="application/atom+xml") 
Example 75
Project: ftd   Author: thisisparker   File: getobits.py    GNU General Public License v3.0 4 votes vote down vote up
def process_obit(obit, past_names, past_headlines):
    obit_source = "The New York Times" 
    # May be more sources in the future, for now just NYT.
    obit_headline = html.unescape(obit['headline']['main'])

    # This line converts NYT's ISO formatted pub_date 
    # to a human-readable format.
    obit_date = datetime.strftime(datetime.strptime(obit['pub_date'],"%Y-%m-%dT%H:%M:%S%z"),"%B %-d, %Y")
    pdf_date = datetime.strftime(datetime.strptime(obit['pub_date'],"%Y-%m-%dT%H:%M:%S%z"),"%Y%m%d")

    # guesses the name of the person by the headline up 
    # until the comma. 
    # Brittle, but matches NYT syntax mostly without fail so far.
    dead_person = obit_headline.split(",")[0] 

    obit_url = obit['web_url']

    doc_request = "A copy of all documents or FBI files pertaining to {dead_person}, an obituary of whom was published in {obit_source} on {obit_date} under the headline \"{obit_headline}\". Please see attached PDF copy of that obituary, which may also be found at {obit_url}.".format(**locals())

    print("\nPreparing a fax with the following request:\n")

    print(doc_request)

    if dead_person in past_names:
        print("\nBut it looks like you've already sent a request for {dead_person}.".format(**locals()))
    elif obit_headline in past_headlines:
        print("\nBut it looks like you've already sent a request for the obit \"{obit_headline}\".".format(**locals()))

    should_request = input("\nLook good? (Y)es/(e)dit/(s)kip/(q)uit ")

    if should_request == "" or should_request == "y" or should_request == "Y":

        now_string = str(datetime.utcnow())

        return [dead_person, doc_request, obit_url, 
            obit_headline, now_string, pdf_date]

    elif should_request == "e":
        new_name = edit_name(obit_headline)
        doc_request = "A copy of all documents or FBI files pertaining to {new_name}, an obituary of whom was published in {obit_source} on {obit_date} under the headline \"{obit_headline}\". Please see attached PDF copy of that obituary, which may also be found at {obit_url}.".format(**locals())
        now_string = str(datetime.utcnow())
        return [new_name, doc_request, obit_url, 
            obit_headline, now_string, pdf_date]

    elif should_request == "s":
        return None

    elif should_request == "q":
        return "q" 
Example 76
Project: geofire-python   Author: ininex   File: test_entries.py    MIT License 4 votes vote down vote up
def test_from_api_repr_w_loggers_no_logger_match(self):
        from datetime import datetime
        from gcloud._helpers import UTC
        klass = self._getTargetClass()
        client = _Client(self.PROJECT)
        PAYLOAD = 'PAYLOAD'
        SEVERITY = 'CRITICAL'
        IID = 'IID'
        NOW = datetime.utcnow().replace(tzinfo=UTC)
        TIMESTAMP = _datetime_to_rfc3339_w_nanos(NOW)
        LOG_NAME = 'projects/%s/logs/%s' % (self.PROJECT, self.LOGGER_NAME)
        LABELS = {'foo': 'bar', 'baz': 'qux'}
        METHOD = 'POST'
        URI = 'https://api.example.com/endpoint'
        STATUS = '500'
        API_REPR = {
            'dummyPayload': PAYLOAD,
            'logName': LOG_NAME,
            'insertId': IID,
            'timestamp': TIMESTAMP,
            'labels': LABELS,
            'severity': SEVERITY,
            'httpRequest': {
                'requestMethod': METHOD,
                'requestUrl': URI,
                'status': STATUS,
            },
        }
        loggers = {}
        entry = klass.from_api_repr(API_REPR, client, loggers=loggers)
        self.assertEqual(entry.payload, PAYLOAD)
        self.assertEqual(entry.insert_id, IID)
        self.assertEqual(entry.timestamp, NOW)
        self.assertEqual(entry.labels, LABELS)
        self.assertEqual(entry.severity, SEVERITY)
        self.assertEqual(entry.http_request['requestMethod'], METHOD)
        self.assertEqual(entry.http_request['requestUrl'], URI)
        self.assertEqual(entry.http_request['status'], STATUS)
        logger = entry.logger
        self.assertTrue(isinstance(logger, _Logger))
        self.assertTrue(logger.client is client)
        self.assertEqual(logger.name, self.LOGGER_NAME)
        self.assertEqual(loggers, {LOG_NAME: logger}) 
Example 77
Project: virtual-kubelet-web-mock-python   Author: stuartleeks   File: app.py    MIT License 4 votes vote down vote up
def nodeConditions():
    utcnow = getutcnow()
    return jsonify([
        { 
            'type': 'Ready',
            'status': 'True',
            'lastHeartbeatTime': utcnow,
            'lastTransitionTime': utcnow,
            'reason': 'KubeletReady',
            'message': 'At your service'
        },
        { 
            'type': 'OutOfDisk',
            'status': 'False',
            'lastHeartbeatTime': utcnow,
            'lastTransitionTime': utcnow,
            'reason': 'KubeletHasSufficientDisk',
            'message': 'Plenty of disk space here'
        },
        { 
            'type': 'MemoryPressure',
            'status': 'False',
            'lastHeartbeatTime': utcnow,
            'lastTransitionTime': utcnow,
            'reason': 'KubeletHasSufficientMemory',
            'message': 'Plenty of memory here'
        },
        { 
            'type': 'DiskPressure',
            'status': 'False',
            'lastHeartbeatTime': utcnow,
            'lastTransitionTime': utcnow,
            'reason': 'KubeletHasNoDiskPressure',
            'message': 'At your service'
        },
        { 
            'type': 'NetworkUnavailable',
            'status': 'False',
            'lastHeartbeatTime': utcnow,
            'lastTransitionTime': utcnow,
            'reason': 'RouteCreated',
            'message': 'Cables all intact'
        },
    ]) 
Example 78
Project: reddit_feed   Author: simon987   File: run.py    GNU General Public License v3.0 4 votes vote down vote up
def stream_thing(prefix, publish_queue, mon_queue=None, start_id=None):
    if start_id is None:
        start_id = read_cursor(prefix)

    logger.info("Starting stream for %s at cursor %s" % (prefix, start_id))

    iterable = reddit_ids(prefix, start_id)

    while True:
        chunk = list(islice(iterable, 100))

        params = {"id": ",".join(chunk)}
        results = reddit.get(API_PATH["info"], params=params)
        if not results:
            logger.warning("No results!")
            continue
        post_time = datetime.utcfromtimestamp(results[0].created_utc)
        now = datetime.utcnow()
        distance = now - post_time

        logger.debug("[+%d] (%s) We are %s away from realtime (%s)" %
                     (len(results), prefix, distance, datetime.fromtimestamp(results[0].created_utc)))
        if distance < REALTIME_DELAY:
            sleep_time = (REALTIME_DELAY - distance).total_seconds()
            logger.info("Sleeping %s seconds" % sleep_time)
            time.sleep(sleep_time)

        update_cursor(results[0].id, prefix)

        for result in results:
            publish_queue.put(result)

        if MONITORING:
            mon_queue.put([{
                "measurement": "reddit",
                "time": str(datetime.utcnow()),
                "tags": {
                    "item_type": prefix,
                },
                "fields": {
                    "item_count": len(results),
                    "distance": distance.total_seconds()
                }
            }]) 
Example 79
Project: RAPIDpy   Author: erdc   File: merge.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def convert(self):
        """
        Copies data from RAPID netCDF output to a CF-compliant netCDF file.
        """
        try:
            log('Processing %s ...' % self.rapid_output_file_list[0])
            time_start_conversion = datetime.utcnow()

            # Validate the raw netCDF file
            log('validating input netCDF file', 'INFO')
            id_len, time_len = self._validate_raw_nc()

            # Initialize the output file (create dimensions and variables)
            log('initializing output', 'INFO')
            self._initialize_output(time_len, id_len)

            self._generate_time_values()

            # copy river ids over
            self.cf_nc.variables[self.output_id_dim_name][:] = \
                self.raw_nc_list[0].get_river_id_array()

            # Populate comid, lat, lon, z
            log('writing comid lat lon z')
            lookup_start = datetime.now()
            self._write_comid_lat_lon_z()
            duration = str((datetime.now() - lookup_start).total_seconds())
            log('Lookup Duration (s): ' + duration)

            # Create a variable for streamflow. This is big, and slows down
            # previous steps if we do it earlier.
            self._copy_streamflow_values()

            # close files
            for raw_nc in self.raw_nc_list:
                raw_nc.close()
            self.cf_nc.close()

            # delete original RAPID output
            remove_files(*self.rapid_output_file_list)

            # rename nc compliant file to original name
            os.rename(self.cf_compliant_file, self.rapid_output_file_list[0])
            log('Time to process %s' %
                (datetime.utcnow()-time_start_conversion))
        except Exception:
            # delete cf RAPID output
            remove_files(self.cf_compliant_file)
            raise 
Example 80
Project: cloud-opensource-python   Author: GoogleCloudPlatform   File: test_pip_checker.py    Apache License 2.0 4 votes vote down vote up
def test_success(self, mock_docker, mock__call_pypi_json_api):
        mock_docker.return_value = MockDockerClient()
        expected_list_output = [{
            'name': 'six',
            'version': '1.2.3',
            'latest_version': '1.2.4',
        }]
        expected_dependency_info = {
            'six': {
                'installed_version': '1.2.3',
                'installed_version_time': '2018-05-10T15:00:00',
                'latest_version': '1.2.4',
                'current_time': '2018-06-13T16:13:33.744591',
                'latest_version_time': '2018-06-13T18:29:51',
                'is_latest': False
            }
        }

        mock_datetime = mock.Mock()
        mock_now = mock.Mock()
        mock_now.isoformat.return_value = '2018-06-13T16:13:33.744591'
        mock_datetime.datetime.utcnow.return_value = mock_now

        patch = mock.patch('pip_checker.datetime', mock_datetime)

        mock__call_pypi_json_api.return_value = {
            'releases': {
                '1.2.4': [
                    {
                        'upload_time': '2018-06-13T18:29:51',
                    },
                ],
                '1.2.3': [
                    {
                        'upload_time': '2018-05-10T15:00:00',
                    }
                ],
            },
        }

        expected_check_result = pip_checker.PipCheckResult(
            packages=['six'],
            result_type=pip_checker.PipCheckResultType.SUCCESS,
            result_text=None,
            dependency_info=expected_dependency_info)

        with patch:
            check_result = pip_checker.check(
                pip_command=[
                    self._fake_pip_path, '--expected-install-args=-U,six',
                    '--freeze-output=six==1.2.3\n',
                    '--list-output={}'.format(
                        json.dumps(expected_list_output))
                ],
                packages=['six'],
                stats=self._stats)
        self.assertEqual(
            check_result,
            expected_check_result)