Python time.strftime() Examples

The following are 30 code examples of time.strftime(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module time , or try the search function .
Example #1
Source File: mlbgamedata.py    From mlbv with GNU General Public License v3.0 7 votes vote down vote up
def _get_header(border, game_date, show_scores, show_linescore):
        header = list()
        date_hdr = '{:7}{} {}'.format('', game_date, datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d"), "%a"))
        if show_scores:
            if show_linescore:
                header.append("{:56}".format(date_hdr))
                header.append('{c_on}{dash}{c_off}'
                              .format(c_on=border.border_color, dash=border.thickdash*92, c_off=border.color_off))
            else:
                header.append("{:48} {:^7} {pipe} {:^5} {pipe} {:^9} {pipe} {}"
                              .format(date_hdr, 'Series', 'Score', 'State', 'Feeds', pipe=border.pipe))
                header.append("{c_on}{}{pipe}{}{pipe}{}{pipe}{}{c_off}"
                              .format(border.thickdash * 57, border.thickdash * 7, border.thickdash * 11, border.thickdash * 16,
                                      pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        else:
            header.append("{:48} {:^7} {pipe} {:^9} {pipe} {}".format(date_hdr, 'Series', 'State', 'Feeds', pipe=border.pipe))
            header.append("{c_on}{}{pipe}{}{pipe}{}{c_off}"
                          .format(border.thickdash * 57, border.thickdash * 11, border.thickdash * 16,
                                  pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        return header 
Example #2
Source File: std.py    From sqliv with GNU General Public License v3.0 7 votes vote down vote up
def stdin(message, params, upper=False, lower=False):
    """ask for option/input from user"""

    symbol = colored("[OPT]", "magenta")
    currentime = colored("[{}]".format(time.strftime("%H:%M:%S")), "green")

    option = raw_input("{} {} {}: ".format(symbol, currentime, message))

    if upper:
        option = option.upper()
    elif lower:
        option = option.lower()

    while option not in params:
        option = raw_input("{} {} {}: ".format(symbol, currentime, message))

        if upper:
            option = option.upper()
        elif lower:
            option = option.lower()

    return option 
Example #3
Source File: standings.py    From mlbv with GNU General Public License v3.0 6 votes vote down vote up
def get_standings(standings_option='all', date_str=None, args_filter=None):
    """Displays standings."""
    LOG.debug('Getting standings for %s, option=%s', date_str, standings_option)
    if date_str == time.strftime("%Y-%m-%d"):
        # strip out date string from url (issue #5)
        date_str = None
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'division'):
        display_division_standings(date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division'))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'wildcard'):
        _display_standings('wildCard', 'Wildcard', date_str, args_filter, rank_tag='wildCardRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'overall') \
            or util.substring_match(standings_option, 'league') or util.substring_match(standings_option, 'conference'):
        _display_standings('byLeague', 'League', date_str, args_filter, rank_tag='leagueRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')

    if util.substring_match(standings_option, 'playoff') or util.substring_match(standings_option, 'postseason'):
        _display_standings('postseason', 'Playoffs', date_str, args_filter)
    if util.substring_match(standings_option, 'preseason'):
        _display_standings('preseason', 'Preseason', date_str, args_filter) 
Example #4
Source File: session.py    From mlbv with GNU General Public License v3.0 6 votes vote down vote up
def save_playlist_to_file(self, stream_url):
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "identity",
            "Accept-Language": "en-US,en;q=0.8",
            "Connection": "keep-alive",
            "User-Agent": self.user_agent,
            "Cookie": self.access_token
        }
        # util.log_http(stream_url, 'get', headers, sys._getframe().f_code.co_name)
        resp = self.session.get(stream_url, headers=headers)
        playlist = resp.text
        playlist_file = os.path.join(util.get_tempdir(), 'playlist-{}.m3u8'.format(time.strftime("%Y-%m-%d")))
        LOG.info('Writing playlist to: %s', playlist_file)
        with open(playlist_file, 'w') as outf:
            outf.write(playlist)
        LOG.debug('save_playlist_to_file: %s', playlist) 
Example #5
Source File: sifter.py    From sandsifter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dump_artifacts(r, injector, command_line):
    global arch
    tee = Tee(LOG, "w")
    tee.write("#\n")
    tee.write("# %s\n" % command_line)
    tee.write("# %s\n" % injector.command)
    tee.write("#\n")
    tee.write("# insn tested: %d\n" % r.ic)
    tee.write("# artf found:  %d\n" % r.ac)
    tee.write("# runtime:     %s\n" % r.elapsed())
    tee.write("# seed:        %d\n" % injector.settings.seed)
    tee.write("# arch:        %s\n" % arch)
    tee.write("# date:        %s\n" % time.strftime("%Y-%m-%d %H:%M:%S"))
    tee.write("#\n")
    tee.write("# cpu:\n")

    cpu = get_cpu_info()
    for l in cpu:
        tee.write("# %s\n" % l) 

    tee.write("# %s  v  l  s  c\n" % (" " * 28))
    for k in sorted(list(r.ad)):
        v = r.ad[k]
        tee.write(result_string(k, v)) 
Example #6
Source File: webcam.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def take_adv_picture(self, num_of_pic, seconds_between):
		logging.debug("Webcam: Trying to take pictures")
		try:
			self.cam.start()
		except SystemError as se: # device path wrong
			logging.error("Webcam: Wasn't able to find video device at device path: %s" % self.path)
			return
		except AttributeError as ae: # init failed, taking pictures won't work -> shouldn't happen but anyway
			logging.error("Webcam: Couldn't take pictures because video device wasn't initialized properly")
			return

		try:
			for i in range(0,num_of_pic):
				img = self.cam.get_image()
				pygame.image.save(img, "%s/%s_%d.jpg" % (self.data_path, time.strftime("%Y%m%d_%H%M%S"), i))
				time.sleep(seconds_between)
		except Exception as e:
			logging.error("Webcam: Wasn't able to take pictures: %s" % e)

		self.cam.stop()
		logging.debug("Webcam: Finished taking pictures") 
Example #7
Source File: datetime.py    From Writer with MIT License 6 votes vote down vote up
def initUI(self):
 
        self.box = QtGui.QComboBox(self)

        for i in self.formats:
            self.box.addItem(strftime(i))

        insert = QtGui.QPushButton("Insert",self)
        insert.clicked.connect(self.insert)
 
        cancel = QtGui.QPushButton("Cancel",self)
        cancel.clicked.connect(self.close)
 
        layout = QtGui.QGridLayout()

        layout.addWidget(self.box,0,0,1,2)
        layout.addWidget(insert,1,0)
        layout.addWidget(cancel,1,1)
        
        self.setGeometry(300,300,400,80)
        self.setWindowTitle("Date and Time")
        self.setLayout(layout) 
Example #8
Source File: stopcron.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
Example #9
Source File: getmetrics_nfdump.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def getFileNameList():
    currentDate = time.strftime("%Y/%m/%d", time.localtime())
    fileNameList = []
    start_time_epoch = long(time.time())
    chunks = int(reportingConfigVars['reporting_interval'] / 5)
    startMin = time.strftime("%Y%m%d%H%M", time.localtime(start_time_epoch))
    closestMinute = closestNumber(int(startMin[-2:]), 5)
    if closestMinute < 10:
        closestMinStr = '0' + str(closestMinute)
        newDate = startMin[:-2] + str(closestMinStr)
    else:
        newDate = startMin[:-2] + str(closestMinute)
    chunks -= 1
    currentTime = datetime.datetime.strptime(newDate, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
    closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
    filename = os.path.join(currentDate, "nfcapd." + closestMinute)
    fileNameList.append(filename)
    while chunks >= 0:
        chunks -= 1
        currentTime = datetime.datetime.strptime(closestMinute, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
        closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
        filename = os.path.join(currentDate, "nfcapd." + closestMinute)
        fileNameList.append(filename)

    return set(fileNameList) - getLastSentFiles() 
Example #10
Source File: getmetrics_kvm.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def checkNewVMs(vmDomains):
    newVMNames = []
    vmMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for vmDomain in vmDomains:
        newVMNames.append(vmDomain.name())
    if os.path.isfile(vmMetaDataFilePath) == False:
        towritePreviousVM = {}
        towritePreviousVM["allVM"] = newVMNames
        with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
            json.dump(towritePreviousVM, vmMetaDataFile)
    else:
        with open(vmMetaDataFilePath, 'r') as vmMetaDataFile:
            oldVMDomains = json.load(vmMetaDataFile)["allVM"]
        if cmp(newVMNames, oldVMDomains) != 0:
            towritePreviousVM = {}
            towritePreviousVM["allVM"] = newVMNames
            with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
                json.dump(towritePreviousVM, vmMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + date + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + date + ".csv")
                newFile = os.path.join(homePath, dataDirectory + date + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
Example #11
Source File: getmetrics_jolokia.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def checkNewInstances(instances):
    newInstances = []
    currentDate = time.strftime("%Y%m%d")
    instancesMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for instance in instances:
        newInstances.append(instance[1])
    if os.path.isfile(instancesMetaDataFilePath) == False:
        towritePreviousInstances = {}
        towritePreviousInstances["allInstances"] = newInstances
        with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
            json.dump(towritePreviousInstances, instancesMetaDataFile)
    else:
        with open(instancesMetaDataFilePath, 'r') as instancesMetaDataFile:
            oldInstances = json.load(instancesMetaDataFile)["allInstances"]
        if cmp(newInstances, oldInstances) != 0:
            towritePreviousInstances = {}
            towritePreviousInstances["allInstances"] = newInstances
            with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
                json.dump(towritePreviousInstances, instancesMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + currentDate + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + currentDate + ".csv")
                newFile = os.path.join(homePath,
                                       dataDirectory + currentDate + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
Example #12
Source File: cpp.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,lexer=None):
        if lexer is None:
            lexer = lex.lexer
        self.lexer = lexer
        self.macros = { }
        self.path = []
        self.temp_path = []

        # Probe the lexer for selected tokens
        self.lexprobe()

        tm = time.localtime()
        self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm))
        self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm))
        self.parser = None

    # -----------------------------------------------------------------------------
    # tokenize()
    #
    # Utility function. Given a string of text, tokenize into a list of tokens
    # ----------------------------------------------------------------------------- 
Example #13
Source File: preprocessor_plugins.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def createBuiltinDefines(lines):
	# Create date-time variables

	timecodes = ['%S', '%M', '%H', '%I', '%p', '%d', '%m', '%Y', '%y', '%B', '%b', '%x', '%X']
	timenames = ['__SEC__','__MIN__','__HOUR__','__HOUR12__','__AMPM__','__DAY__','__MONTH__','__YEAR__','__YEAR2__','__LOCALE_MONTH__','__LOCALE_MONTH_ABBR__','__LOCALE_DATE__','__LOCALE_TIME__']
	defines = ['define {0} := \"{1}\"'.format(timenames[i], strftime(timecodes[i], localtime())) for i in range(len(timecodes))]

	newLines = collections.deque()

	# append our defines on top of the script in a temporary deque
	for string in defines:
		newLines.append(lines[0].copy(string))

	# merge with the original unmodified script
	for line in lines:
		newLines.append(line)

	# replace original deque with modified one
	replaceLines(lines, newLines)

#================================================================================================= 
Example #14
Source File: summary.py    From BatteryMonitor with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
    self.currenttime = time.localtime()
    printtime = time.strftime("%Y%m%d%H%M%S ", self.currenttime)
    self.logfile = open(config['files']['logfile'],'at',buffering=1)
    self.sampletime = time.time()
    self.prevtime = time.localtime()
    self.summary=loadsummary()

#      summary = open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/summary','w')
#      pickle.dump(hivolts, summary)
#      pickle.dump(lowvolts, summary)
#      summary.close()
    if self.summary['hour']['timestamp'][0:10] != printtime[0:10]:
      self.summary['hour'] = deepcopy(self.summary['current'])
    if self.summary['currentday']['timestamp'][0:8] != printtime[0:8]:
      self.summary['currentday'] = deepcopy(self.summary['current'])
    if self.summary['monthtodate']['timestamp'][0:6] != printtime[0:6]:
      self.summary['monthtodate'] = deepcopy(self.summary['current'])
    if self.summary['yeartodate']['timestamp'][0:4] != printtime[0:4]:
      self.summary['yeartodate'] = deepcopy(self.summary['current']) 
Example #15
Source File: getbms.py    From BatteryMonitor with GNU General Public License v2.0 6 votes vote down vote up
def getbmsdat(self,port,command):
    """ Issue BMS command and return data as byte data """
    """ assumes data port is open and configured """
    for i in range(5):
      try:
        port.write(command)
        reply = port.read(4)
#        raise serial.serialutil.SerialException('hithere')
        break
      except serial.serialutil.SerialException as err:
        errfile=open(config['files']['errfile'],'at')
        errfile.write(time.strftime("%Y%m%d%H%M%S ", time.localtime())+str(err.args)+'\n')
        errfile.close()

  #  print (reply)
    x = int.from_bytes(reply[3:5], byteorder = 'big')
#    print (x)
    data = port.read(x)
    end = port.read(3)
#    print (data)
    return data 
Example #16
Source File: download.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _StoreDebugInfo(self, file_stream, socket_error=None):
    """Gathers debug information for use when file downloads fail.

    Args:
      file_stream:  The file stream object of the file being downloaded.
      socket_error: Store the error raised from the socket class with
        other debug info.

    Returns:
      debug_info:  A dictionary containing various pieces of debugging
          information.
    """
    if socket_error:
      self._debug_info['socket_error'] = socket_error
    if file_stream:
      for header in file_stream.info().header_items():
        self._debug_info[header[0]] = header[1]
    self._debug_info['current_time'] = time.strftime(
        '%A, %d %B %Y %H:%M:%S UTC') 
Example #17
Source File: study_robot.py    From 21tb_robot with MIT License 5 votes vote down vote up
def log(info):
    """simple log"""
    print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), info
    sys.stdout.flush() 
Example #18
Source File: mlbgamedata.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def process_game_data(self, game_date, num_days=1):
        game_days_list = list()
        for i in range(0, num_days):
            game_records = self._get_games_by_date(game_date)
            if game_records is not None:
                game_days_list.append((game_date, game_records))
            game_date = datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d") + timedelta(days=1), "%Y-%m-%d")
        return game_days_list 
Example #19
Source File: standings.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def _display_standings(standings_type, display_title, date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division')):
    if date_str is None:
        season_str = time.strftime("%Y")
        url_date_str = ''
    else:
        season_str = datetime.strftime(datetime.strptime(date_str, "%Y-%m-%d"), "%Y")
        url_date_str = '&date=' + date_str
    url = STANDINGS_URL.format(standings_type=standings_type,
                               league_ids=mlbapidata.get_league_ids(args_filter),
                               season=season_str, date=url_date_str)
    json_data = request.request_json(url, 'standings-{}-{}'.format(season_str, standings_type), cache_stale=request.CACHE_SHORT)

    border = displayutil.Border(use_unicode=config.UNICODE)

    outl = list()
    if display_title != '':
        outl.append(_get_title_header(display_title, border))

    needs_line_hr = False
    for record in json_data['records']:
        if args_filter and standings_type == 'byDivision' and args_filter in mlbapidata.DIVISION_FILTERS:
            pass

        _get_standings_display_for_record(outl, standings_type, record, header_tags, rank_tag, border, needs_line_hr)

    print('\n'.join(outl)) 
Example #20
Source File: standings.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def display_division_standings(date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division')):
    standings_type = 'byDivision'
    display_title = 'Division'
    if date_str is None:
        season_str = time.strftime("%Y")
        url_date_str = ''
    else:
        season_str = datetime.strftime(datetime.strptime(date_str, "%Y-%m-%d"), "%Y")
        url_date_str = '&date=' + date_str
    url = STANDINGS_URL.format(standings_type=standings_type,
                               league_ids=mlbapidata.get_league_ids(args_filter),
                               season=season_str, date=url_date_str)
    json_data = request.request_json(url, 'standings-{}-{}'.format(season_str, standings_type), cache_stale=request.CACHE_SHORT)

    border = displayutil.Border(use_unicode=config.UNICODE)

    outl = list()
    if display_title != '':
        outl.append(_get_title_header(display_title, border))

    needs_line_hr = False
    if args_filter and args_filter in mlbapidata.DIVISION_FILTERS:
        _get_standings_display_for_record(outl, standings_type,
                                          _get_division_record(json_data['records'], args_filter),
                                          header_tags, rank_tag, border, needs_line_hr)
    else:
        for div in mlbapidata.DIVISION_FILTERS:
            div_record = _get_division_record(json_data['records'], div)
            if div_record:
                _get_standings_display_for_record(outl, standings_type, div_record,
                                                  header_tags, rank_tag, border, needs_line_hr)
    print('\n'.join(outl)) 
Example #21
Source File: util.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def convert_time_to_local(d):
    from_zone = tz.tzutc()
    to_zone = tz.tzlocal()
    utc = d.replace(tzinfo=from_zone)
    if config.CONFIG.parser['timeformat'] == '12H':
        return utc.astimezone(to_zone).strftime('%I:%M %p').replace('PM', 'pm').replace('AM', 'am')
    return utc.astimezone(to_zone).strftime('%H:%M') 
Example #22
Source File: local.py    From ALF with Apache License 2.0 5 votes vote down vote up
def local_run():
    opts, arg_error = parse_args()
    if opts.verbose:
        log.getLogger().setLevel(log.DEBUG)
    proj_cls = load_project(opts.project_name)
    if opts.reduce:
        for r in opts.reduce:
            if r not in reducers:
                arg_error("unknown reducer: \"%r\"" % r)

    tmp_wd = os.getcwd()
    if os.path.isdir(opts.template_or_directory):
        test_dir = os.path.abspath(opts.template_or_directory)
        tests = [os.path.join(test_dir, test) for test in os.listdir(opts.template_or_directory)]
        run_folder = "%s_%s_dir_replay" % (time.strftime("%Y%m%d-%H%M%S"), opts.project_name)
    else:
        tests = [opts.template_or_directory]
        run_folder = "%s_%s_local" % (time.strftime("%Y%m%d-%H%M%S"), opts.project_name)

    os.mkdir(run_folder)
    for template_fn in tests:
        template_fn = os.path.abspath(template_fn)
        os.chdir(run_folder)
        main(opts.project_name, proj_cls(template_fn), run_folder, template_fn,
             opts.iterations, opts.min_aggr, opts.max_aggr, opts.keep_mutations, opts.timeout,
             opts.pickle_result, opts.reduce, opts.reducen)
        os.chdir(tmp_wd) 
Example #23
Source File: main.py    From controllable-text-attribute-transfer with Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example #24
Source File: main.py    From controllable-text-attribute-transfer with Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        pass
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example #25
Source File: main.py    From controllable-text-attribute-transfer with Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example #26
Source File: main.py    From controllable-text-attribute-transfer with Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        args.data_path = '../../data/imagecaption/processed_files/'
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example #27
Source File: main.py    From controllable-text-attribute-transfer with Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example #28
Source File: cpstats.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def locale_date(v):
    return time.strftime('%c', time.gmtime(v)) 
Example #29
Source File: cpstats.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iso_format(v):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(v)) 
Example #30
Source File: facerec_from_webcam_mult_thread.py    From face-attendance-machine with Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    此处会碰到全局并发,导致锁的问题
    :param name:
    :return:
    """
    return
    print('process_face_records start', time.time())

    global current_names, last_time
    # myprint("global current_names {}, last_time {}".format(current_names, last_time))

    # 判断是不是在识别的列表中,不在的话就进行问候
    if name not in current_names:
        print("ts ====", last_time, time.time())
        current_names.append(name)
        myprint("Hello {}, nice to meet you! ".format(name))
        # speaker.Speak("Hello {}, nice to meet you! ".format(name))

    # 在一定时间内,清空已经识别的人, 并进行
    if last_time < time.time() - TIME_DIFF:  # 每隔一段时间清空一下检测到的人
        last_time = time.time()
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        myprint(time_format + " update last_time and clear current_names.")
        with open(name_record, 'a') as f:
            if len(current_names) > 0:
                f.writelines("{}:{} \n".format(time_format, str(current_names)))
        print("======", current_names)
        current_names = []  # clear()
        current_names = [name]
        myprint('process_face_records end', time.time())