How to use the datetime.datetime.utcnow function in DateTime

To help you get started, we’ve selected a few DateTime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zillow / ctds / tests / test_cursor_callproc.py View on Github external
types = [str]
                    if not PY3: # pragma: nocover
                        types.append(unicode_)
                    for type_ in types:
                        inputs = {
                            type_('@pBigInt'): ctds.Parameter(12345, output=True),
                            type_('@pVarChar'): ctds.Parameter(
                                unicode_('hello world, how\'s it going! '),
                                output=True
                            ),
                            type_('@pVarBinary'): ctds.Parameter(ctds.SqlVarBinary(None, size=32), output=True),
                            type_('@pFloat'): ctds.Parameter(1.23, output=True),
                            type_('@pDateTime'): datetime(2011, 11, 5, 12, 12, 12),
                            type_('@pDateTimeOut'): ctds.Parameter(datetime(2011, 11, 5, 12, 12, 12), output=True),
                            type_('@pDateTime2'): datetime(2011, 11, 5, 12, 12, 12, 999999),
                            type_('@pDateTime2Out'): ctds.Parameter(datetime.utcnow(), output=True),
                            type_('@pDate'): date(2011, 11, 5),
                            type_('@pDateOut'): ctds.Parameter(date.today(), output=True),
                            type_('@pTime'): time(12, 12, 12, 123456),
                            type_('@pTimeOut'): ctds.Parameter(datetime.utcnow().time(), output=True),
                        }
                        outputs = cursor.callproc(sproc, inputs)
                        self.assertNotEqual(id(outputs[type_('@pBigInt')]), id(inputs[type_('@pBigInt')]))
                        self.assertNotEqual(id(outputs[type_('@pVarChar')]), id(inputs[type_('@pVarChar')]))
                        self.assertNotEqual(id(outputs[type_('@pVarBinary')]), id(inputs[type_('@pVarBinary')]))
                        self.assertEqual(id(outputs[type_('@pDateTime')]), id(inputs[type_('@pDateTime')]))
                        self.assertEqual(id(outputs[type_('@pDateTime2')]), id(inputs[type_('@pDateTime2')]))
                        self.assertEqual(id(outputs[type_('@pDate')]), id(inputs[type_('@pDate')]))
                        self.assertEqual(id(outputs[type_('@pTime')]), id(inputs[type_('@pTime')]))

                        self.assertEqual(
                            outputs[type_('@pBigInt')],
github miguelgrinberg / microblog / app / main / routes.py View on Github external
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()
        g.search_form = SearchForm()
    g.locale = str(get_locale())
github rucio / rucio / lib / rucio / core / replica.py View on Github external
:param session: The database session in use.

    :returns: a list of dictionary replica.
    """
    if not rse_id:
        rse_id = get_rse_id(rse=rse, session=session)

    # filter(models.RSEFileAssociation.state != ReplicaState.BEING_DELETED).\
    none_value = None  # Hack to get pep8 happy...
    query = session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.path, models.RSEFileAssociation.bytes, models.RSEFileAssociation.tombstone, models.RSEFileAssociation.state).\
        with_hint(models.RSEFileAssociation, "INDEX_RS_ASC(replicas REPLICAS_TOMBSTONE_IDX)  NO_INDEX_FFS(replicas REPLICAS_TOMBSTONE_IDX)", 'oracle').\
        filter(models.RSEFileAssociation.tombstone < datetime.utcnow()).\
        filter(models.RSEFileAssociation.lock_cnt == 0).\
        filter(case([(models.RSEFileAssociation.tombstone != none_value, models.RSEFileAssociation.rse_id), ]) == rse_id).\
        filter(or_(models.RSEFileAssociation.state.in_((ReplicaState.AVAILABLE, ReplicaState.UNAVAILABLE, ReplicaState.BAD)),
                   and_(models.RSEFileAssociation.state == ReplicaState.BEING_DELETED, models.RSEFileAssociation.updated_at < datetime.utcnow() - timedelta(seconds=delay_seconds)))).\
        order_by(models.RSEFileAssociation.tombstone)

    # do no delete files used as sources
    stmt = exists(select([1]).prefix_with("/*+ INDEX(requests REQUESTS_SCOPE_NAME_RSE_IDX) */", dialect='oracle')).\
        where(and_(models.RSEFileAssociation.scope == models.Request.scope,
                   models.RSEFileAssociation.name == models.Request.name))
    query = query.filter(not_(stmt))

    if worker_number and total_workers and total_workers - 1 > 0:
        if session.bind.dialect.name == 'oracle':
            bindparams = [bindparam('worker_number', worker_number - 1), bindparam('total_workers', total_workers - 1)]
            query = query.filter(text('ORA_HASH(name, :total_workers) = :worker_number', bindparams=bindparams))
        elif session.bind.dialect.name == 'mysql':
            query = query.filter(text('mod(md5(name), %s) = %s' % (total_workers - 1, worker_number - 1)))
        elif session.bind.dialect.name == 'postgresql':
            query = query.filter(text('mod(abs((\'x\'||md5(name))::bit(32)::int), %s) = %s' % (total_workers - 1, worker_number - 1)))
github NaturalHistoryMuseum / inselect / inselect / gui / main_window.py View on Github external
if path:
            path = Path(path)
            document = InselectDocument.load(path)
        else:
            path = document.document_path

        debug_print('MainWindow.open_document [{0}]'.format(path))
        QSettings().setValue("working_directory", str(path.parent))

        self.model.from_document(document)

        self.document = document
        self.document_path = path

        self.time_doc_opened = datetime.utcnow()

        self.setWindowTitle('')
        self.setWindowFilePath(str(self.document_path))
        self.info_widget.set_document(self.document)

        RecentDocuments().add_path(path)
        self._sync_recent_documents_actions()

        self.zoom_home()

        self.sync_ui()

        if not is_writable(path):
            msg = ('The file [{0}] is read-only.\n\n'
                   'You will not be able to save any changes that you make.')
            msg = msg.format(path.name)
github closeio / tz-trout / tztrout / data.py View on Github external
def _experiences_dst(self, tz):
        """Check if the time zone identifier has experienced the DST in the
        recent years.
        """
        dt = datetime.datetime.utcnow()
        while dt.year > self.RECENT_YEARS_START:
            try:
                dst = tz.dst(dt).total_seconds()
                if dst:
                    return True
            except (pytz.NonExistentTimeError, pytz.AmbiguousTimeError):
                pass
            dt -= datetime.timedelta(**self.TD_STEP)
        return False
github VOLTTRON / volttron / volttron / platform / agent / utils.py View on Github external
def get_aware_utc_now():
    """Create a timezone aware UTC datetime object from the system time.
    
    :returns: an aware UTC datetime object
    :rtype: datetime
    """
    utcnow = datetime.utcnow()
    utcnow = pytz.UTC.localize(utcnow)
    return utcnow
github readthedocs / readthedocs.org / readthedocs / doc_builder / environments.py View on Github external
# reporting
            if self.failure and isinstance(
                    self.failure,
                    BuildEnvironmentException,
            ):
                self.build['exit_code'] = self.failure.status_code
            elif self.commands:
                self.build['exit_code'] = max([
                    cmd.exit_code for cmd in self.commands
                ])

        self.build['setup'] = self.build['setup_error'] = ''
        self.build['output'] = self.build['error'] = ''

        if self.start_time:
            build_length = (datetime.utcnow() - self.start_time)
            self.build['length'] = int(build_length.total_seconds())

        if self.failure is not None:
            # Surface a generic error if the class is not a
            # BuildEnvironmentError
            # yapf: disable
            if not isinstance(
                self.failure,
                (
                    BuildEnvironmentException,
                    BuildEnvironmentWarning,
                ),
            ):
                # yapf: enable
                log.error(
                    'Build failed with unhandled exception: %s',
github GoogleCloudPlatform / cloud-pubsub-samples-python / gce-cmdline-publisher / traffic_pubsub_generator.py View on Github external
print "%s lines processed" % line_count
            ts = ""
            try:
                timestring = line[0]
                orig_date = parse(timestring)
                if current:  # if using --current flag
                    (line, ts) = process_current_mode(
                        orig_date, diff, line, replay, random_delays)
                else:  # not using --current flag
                    (line, ts) = process_noncurrent_mode(
                        orig_date, line, random_delays)

                if replay and orig_date != prev_date:
                    date_delta = orig_date - prev_date
                    print "date delta: %s" % date_delta.total_seconds()
                    current_time = datetime.datetime.utcnow()
                    timelapse = current_time - restart_time
                    print "timelapse: %s" % timelapse.total_seconds()
                    d2 = date_delta - timelapse
                    sleeptime = d2.total_seconds()
                    print "sleeping %s" % sleeptime
                    time.sleep(sleeptime)
                    restart_time = datetime.datetime.utcnow()
                    print "restart_time is set to: %s" % restart_time
                prev_date = orig_date
                msg_attributes = {'timestamp': ts}
                publish(client, pubsub_topic, ",".join(line), msg_attributes)
                if incidents:  # if generating traffic 'incidents' as well
                    # randomly determine whether we'll generate an incident
                    # associated with this reading.
                    if random.random() < INCIDENT_THRESH:
                        print "Generating a traffic incident for %s." % line
github PythonCharmers / python-future / src / future / backports / http / cookiejar.py View on Github external
def time2isoz(t=None):
    """Return a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
    representing Universal Time (UTC, aka GMT).  An example of this format is:

    1994-11-24 08:49:37Z

    """
    if t is None:
        dt = datetime.datetime.utcnow()
    else:
        dt = datetime.datetime.utcfromtimestamp(t)
    return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
github cuemacro / findatapy / findatapy / market / marketdatagenerator.py View on Github external
def fetch_single_time_series(self, market_data_request):

        market_data_request = MarketDataRequest(md_request=market_data_request)

        # only includes those tickers have not expired yet!
        start_date = pandas.Timestamp(market_data_request.start_date).date()

        import datetime

        current_date = datetime.datetime.utcnow().date()

        from datetime import timedelta

        tickers = market_data_request.tickers
        vendor_tickers = market_data_request.vendor_tickers

        expiry_date = market_data_request.expiry_date

        config = ConfigManager().get_instance()

        # in many cases no expiry is defined so skip them
        for i in range(0, len(tickers)):
            try:
                expiry_date = config.get_expiry_for_ticker(market_data_request.data_source, tickers[i])
            except:
                pass