How to use the datetime.datetime.today 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 Luxoft / Twister / server / CeXmlRpc.py View on Github external
"""
        logFull('CeXmlRpc:get_exec_status_all user `{}`.'.format(user))
        data = self.project.get_user_info(user)
        rev_dict = dict((v, k) for k, v in EXEC_STATUS.iteritems())
        status = rev_dict[data.get('status', 8)]

        # If start time is not define, then define it
        if not data.get('start_time'):
            start_time = datetime.datetime.today()
            self.project.set_user_info(user, 'start_time', start_time.strftime('%Y-%m-%d %H:%M:%S'))
        else:
            start_time = datetime.datetime.strptime(data['start_time'], '%Y-%m-%d %H:%M:%S')

        # If the engine is not stopped, update elapsed time
        if data.get('status', 8) != STATUS_STOP:
            elapsed_time = str(datetime.datetime.today() - start_time).split('.')[0]
            self.project.set_user_info(user, 'elapsed_time', elapsed_time)
        else:
            elapsed_time = data.get('elapsed_time', 0)

        # Status + start time + elapsed time
        start_time = start_time.strftime('%Y-%m-%d %H:%M:%S')

        return '{0}; {1}; {2}; {3};'.format(status, start_time, elapsed_time, data.get('started_by', 'X'))
github rethinkdb / rethinkdb / drivers / python / rethinkdb / _dump.py View on Github external
# Check validity of arguments
    if len(args) != 0:
        raise RuntimeError("Error: No positional arguments supported. Unrecognized option '%s'" % args[0])

    if options.help:
        print_dump_help()
        exit(0)

    res = { }

    # Verify valid host:port --connect option
    (res["host"], res["port"]) = parse_connect_option(options.host)

    # Verify valid output file
    res["temp_filename"] = "rethinkdb_dump_%s" % datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S")
    if options.out_file is None:
        res["out_file"] = os.path.abspath("./" + res["temp_filename"] + ".tar.gz")
    else:
        res["out_file"] = os.path.abspath(options.out_file)

    if os.path.exists(res["out_file"]):
        raise RuntimeError("Error: Output file already exists: %s" % res["out_file"])

    # Verify valid client count
    if options.clients < 1:
       raise RuntimeError("Error: invalid number of clients (%d), must be greater than zero" % options.clients)
    res["clients"] = options.clients

    # Make sure the temporary directory exists and is accessible
    res["temp_dir"] = options.temp_dir
github zacharydenton / 750words / sevenfifty / main.py View on Github external
def get_path(self, date=None):
        if date is None:
            date = datetime.datetime.today()
        file_format = "txt"
        path = os.path.join(self.output_dir, "%04i-%02i-%02i" % (date.year, date.month, date.day) + '.' + file_format) 
        return path
github spsu / sylph / core / node / api.py View on Github external
Another node is asking us for a key so they can make priveledged
	transactions with us. They'll have to verify this with us.
	"""
	# TODO: THIS IS TERRIBLE!
	p = request.POST
	uri = hashless(p['uri'])
	#key_theirs = p['key'] if 'key' in p else None

	# Lookup or create node.
	# TODO: For now assume it exists. Must deal with spam/fraud later.
	node = None
	try:
		node = Node.objects.get(uri=uri)
	except Node.DoesNotExist:
		node = Node(uri=uri)
		node.datetime_added = datetime.today()
		node.is_yet_to_resolve = True
		#node.save()

	# XXX: We cannot give them the key in this transaction as anyone could
	# be making it. We'll have to request the node over HTTP.
	key = Node.generate_key()

	# Maybe they want a new key
	if node.key_ours and node.key_ours_confirmed:
		node.new_key_ours = key
		node.save()
		# TODO: Schedule a job to confirm the key 
		return

	node.key_ours = key
	node.key_ours_confirmed = False
github hydroshare / hydroshare / django_irods / views.py View on Github external
istorage = res.get_irods_storage()
    if res.is_federated:
        irods_path = os.path.join(res.resource_federation_path, path)
    else:
        irods_path = path
    # in many cases, path and output_path are the same.
    output_path = path

    irods_output_path = irods_path
    # folder requests are automatically zipped
    if not is_bag_download and not is_zip_download:  # path points into resource: should I zip it?
        store_path = u'/'.join(split_path_strs[1:])  # data/contents/{path-to-something}
        if res.is_folder(store_path):  # automatically zip folders
            is_zip_request = True
            daily_date = datetime.datetime.today().strftime('%Y-%m-%d')
            output_path = "zips/{}/{}/{}.zip".format(daily_date, uuid4().hex, path)
            if res.is_federated:
                irods_output_path = os.path.join(res.resource_federation_path, output_path)
            else:
                irods_output_path = output_path
            if __debug__:
                logger.debug("automatically zipping folder {} to {}".format(path, output_path))
        elif istorage.exists(irods_path):
            if __debug__:
                logger.debug("request for single file {}".format(path))
            is_sf_request = True

            # check for single file aggregations
            if "data/contents/" in path:  # not a metadata file
                for f in ResourceFile.objects.filter(object_id=res.id):
                    if path == f.storage_path:
github msitt / blpapi-python / examples / IntradayTickExample.py View on Github external
elif msg.messageType() == TOKEN_FAILURE:
                break

    if not token:
        print("Failed to get token")
        return False

    # Create and fill the authorization request
    authRequest = authService.createAuthorizationRequest()
    authRequest.set(TOKEN, token)

    # Send authorization request to "fill" the Identity
    session.sendAuthorizationRequest(authRequest, identity, cid)

    # Process related responses
    startTime = datetime.datetime.today()
    WAIT_TIME_SECONDS = 10
    while True:
        event = session.nextEvent(WAIT_TIME_SECONDS * 1000)
        if event.eventType() == blpapi.Event.RESPONSE or \
            event.eventType() == blpapi.Event.REQUEST_STATUS or \
                event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
            for msg in event:
                print(msg)
                if msg.messageType() == AUTHORIZATION_SUCCESS:
                    return True
                print("Authorization failed")
                return False

        endTime = datetime.datetime.today()
        if endTime - startTime > datetime.timedelta(seconds=WAIT_TIME_SECONDS):
            return False
github DingGuodong / LinuxBashShellScriptForOps / functions / date / date.py View on Github external
add_years = datetime.datetime.today() + relativedelta(years=+6)
add_hours = datetime.datetime.today() + relativedelta(hours=+6)
add_mins = datetime.datetime.today() + relativedelta(minutes=+6)
add_seconds = datetime.datetime.today() + relativedelta(seconds=+6)
print("Current Date Time:", datetime.datetime.today())
print("Add 6 days:", add_days)
print("Add 6 months:", add_months)
print("Add 6 years:", add_years)
print("Add 6 hours:", add_hours)
print("Add 6 mins:", add_mins)
print("Add 6 seconds:", add_seconds)

# Python's program to subtract N year month day hour min sec to date.
sub_days = datetime.datetime.today() + relativedelta(days=-6)
sub_months = datetime.datetime.today() + relativedelta(months=-6)
sub_years = datetime.datetime.today() + relativedelta(years=-6)
sub_hours = datetime.datetime.today() + relativedelta(hours=-6)
sub_mins = datetime.datetime.today() + relativedelta(minutes=-6)
sub_seconds = datetime.datetime.today() + relativedelta(seconds=-6)
print("Current Date Time:", datetime.datetime.today())
print("Subtract 6 days:", sub_days)
print("Subtract 6 months:", sub_months)
print("Subtract 6 years:", sub_years)
print("Subtract 6 hours:", sub_hours)
print("Subtract 6 mins:", sub_mins)
print("Subtract 6 seconds:", sub_seconds)

# Python's program to weekday of first day of the month and
# number of days in month, for the specified year and month.
print("Year:2002 - Month:2")
month_range = calendar.monthrange(2002, 2)
print("Weekday of first day of the month:", month_range[0])
github vanheeringen-lab / gimmemotifs / gimmemotifs / report.py View on Github external
report_motifs.append(rm)

    total_report = os.path.join(outdir, "gimme.denovo.html")

    star_img = os.path.join(config.get_template_dir(), "star.png")
    shutil.copyfile(star_img, os.path.join(outdir, "images", "star.png"))

    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader([config.get_template_dir()])
    )
    template = env.get_template("report_template.jinja.html")
    # TODO: title
    result = template.render(
        motifs=report_motifs,
        inputfile=inputfile,
        date=datetime.today().strftime("%d/%m/%Y"),
        version=__version__,
        bg_types=list(background.keys()),
    )

    with open(total_report, "wb") as f:
        f.write(result.encode("utf-8"))
github akrherz / iem / htdocs / plotting / auto / scripts100 / p107.py View on Github external
def get_description():
    """ Return a dict describing how to call this plotter """
    desc = dict()
    desc["data"] = True
    desc[
        "description"
    ] = """This plot presents statistics for a period of
    days each year provided your start date and number of days after that
    date. If your period crosses a year bounds, the plotted year represents
    the year of the start date of the period.

    <br><br>This autoplot is specific to data from COOP stations, a
    similiar autoplot <a href="/plotting/auto/?q=140">#140</a> exists for
    automated stations.
    """
    today = datetime.datetime.today() - datetime.timedelta(days=1)
    desc["arguments"] = [
        dict(
            type="station",
            name="station",
            default="IATDSM",
            label="Select Station",
            network="IACLIMATE",
        ),
        dict(
            type="month",
            name="month",
            default=(today - datetime.timedelta(days=14)).month,
            label="Start Month:",
        ),
        dict(
            type="day",
github FluidSense / SeatMaster / backend / services / applicationSeasonService.py View on Github external
def getCurrentOrNext():
    seasons = db.session.query(ApplicationSeason)
    comingSeasons = seasons.filter(ApplicationSeason.applicationPeriodEnd > datetime.today()).all()
    # Find season with closest application start date to today, by comparing date differences
    return min(comingSeasons, key=lambda season: season.applicationPeriodStart - datetime.today(), default=None)