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)