Python time.strftime() Examples

The following are code examples for showing how to use time.strftime(). 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: mlbv   Author: kmac   File: mlbgamedata.py    GNU General Public License v3.0 6 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
Project: mlbv   Author: kmac   File: standings.py    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 3
Project: mlbv   Author: kmac   File: session.py    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 4
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 5
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_date_time(self):
        # Check that LC_date_time, LC_date, and LC_time are correct
        # the magic date is used so as to not have issues with %c when day of
        #  the month is a single digit and has a leading space.  This is not an
        #  issue since strptime still parses it correctly.  The problem is
        #  testing these directives for correctness by comparing strftime
        #  output.
        magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0)
        strftime_output = time.strftime("%c", magic_date)
        self.assertEqual(time.strftime(self.LT_ins.LC_date_time, magic_date),
                         strftime_output, "LC_date_time incorrect")
        strftime_output = time.strftime("%x", magic_date)
        self.assertEqual(time.strftime(self.LT_ins.LC_date, magic_date),
                         strftime_output, "LC_date incorrect")
        strftime_output = time.strftime("%X", magic_date)
        self.assertEqual(time.strftime(self.LT_ins.LC_time, magic_date),
                         strftime_output, "LC_time incorrect")
        LT = _strptime.LocaleTime()
        LT.am_pm = ('', '')
        self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle "
                                    "empty strings") 
Example 6
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_timezone(self):
        # Test timezone directives.
        # When gmtime() is used with %Z, entire result of strftime() is empty.
        # Check for equal timezone names deals with bad locale info when this
        # occurs; first found in FreeBSD 4.4.
        strp_output = _strptime._strptime_time("UTC", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        strp_output = _strptime._strptime_time("GMT", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        time_tuple = time.localtime()
        strf_output = time.strftime("%Z")  #UTC does not have a timezone
        strp_output = _strptime._strptime_time(strf_output, "%Z")
        locale_time = _strptime.LocaleTime()
        if time.tzname[0] != time.tzname[1] or not time.daylight:
            self.assertTrue(strp_output[8] == time_tuple[8],
                            "timezone check failed; '%s' -> %s != %s" %
                             (strf_output, strp_output[8], time_tuple[8]))
        else:
            self.assertTrue(strp_output[8] == -1,
                            "LocaleTime().timezone has duplicate values and "
                             "time.daylight but timezone value not set to -1") 
Example 7
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_strftime(self):
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = ' %' + directive
            try:
                time.strftime(format, tt)
            except ValueError:
                self.fail('conversion specifier: %r failed.' % format)

        # Issue #10762: Guard against invalid/non-supported format string
        # so that Python don't crash (Windows crashes when the format string
        # input to [w]strftime is not kosher.
        if sys.platform.startswith('win'):
            with self.assertRaises(ValueError):
                time.strftime('%f') 
Example 8
Project: cloudlog   Author: navoshta   File: cloudlog.py    MIT License 6 votes vote down vote up
def __init__(self, root_path, dropbox_token=None, telegram_token=None, telegram_chat_id=None):
        """
        Initialises a new logger instance.

        Parameters
        ----------
        root_path           :
                              Local log root path.
        dropbox_token       :
                              Dropbox access token.
        telegram_token      :
                              Telegram Bot API access token.
        telegram_chat_id    :
                              Telegram chat ID.
        """
        self.telegram_chat_id = int(telegram_chat_id) if telegram_chat_id is not None else None
        self.cloud_log_writer = dropbox.Dropbox(dropbox_token) if dropbox_token is not None else None
        self.notification_bot = TelegramBot(telegram_token) if telegram_token is not None else None

        self.log_file = time.strftime('%Y-%m-%d_%H-%M-%S') + '_log.txt'
        self.root = root_path
        os.makedirs(root_path, exist_ok=True) 
Example 9
Project: sandsifter   Author: Battelle   File: sifter.py    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 10
Project: MercrediFiction   Author: bortzmeyer   File: mercredifiction2others.py    GNU General Public License v2.0 5 votes vote down vote up
def formatdate(str, short=False):
    try:
        bdate = time.strptime(cleandate(str), RFC3339DATETIME)
    except ValueError:
        bdate = time.strptime(cleandate(str), RFC3339DATE)
    if short:
        return time.strftime("%d %B %Y", bdate)
    else:
        return time.strftime("%d %B %Y à %H h %M UTC", bdate) 
Example 11
Project: MercrediFiction   Author: bortzmeyer   File: faireindex.py    GNU General Public License v2.0 5 votes vote down vote up
def formatdate(str):
    bdate = time.strptime(str, RFC3339DATE)
    return time.strftime("%d %B %Y", bdate) 
Example 12
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    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 13
Project: Coulomb   Author: DynamoDS   File: uses_list_at_level.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 14
Project: Coulomb   Author: DynamoDS   File: list_tags_sessions.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 15
Project: Coulomb   Author: DynamoDS   File: list_tags.py    MIT License 5 votes vote down vote up
def log(s):
	if VERBOSE:
		print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 16
Project: Coulomb   Author: DynamoDS   File: list_data_by_tag.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 17
Project: Coulomb   Author: DynamoDS   File: extract_deltas.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 18
Project: Coulomb   Author: DynamoDS   File: session_merger.py    MIT License 5 votes vote down vote up
def log(s):
  if VERBOSE:
    print (time.strftime("%Y-%m-%d %H:%M:%S") + " " + str(s)) 
Example 19
Project: Coulomb   Author: DynamoDS   File: sort_sessions.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 20
Project: Coulomb   Author: DynamoDS   File: extract_sessions.py    MIT License 5 votes vote down vote up
def log(s):
    if VERBOSE:
        print time.strftime("%Y-%m-%d %H:%M:%S"), s 
Example 21
Project: Coulomb   Author: DynamoDS   File: storage_utils.py    MIT License 5 votes vote down vote up
def log(s):
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ": " + s) 
Example 22
Project: Coulomb   Author: DynamoDS   File: data_files_to_sessions.py    MIT License 5 votes vote down vote up
def log(s):
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ": " + s) 
Example 23
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pretty_time(time, now=datetime.datetime.now()):
    tomorrow = now + datetime.timedelta(days=1)
    next_day = now + datetime.timedelta(days=2)
    next_week = now + datetime.timedelta(weeks=1)
    pretty_fmt = '%-I:%M %p'
    pretty_prefix = ''
    if tomorrow < time < next_day:
        pretty_prefix = 'tomorrow at '
    elif time > next_day and time < next_week:
        pretty_prefix = '%A at '
    elif time > next_week and time.month == now.month and time.year == now.year:
        pretty_prefix = '%A the %-d' + pretty_suffix(time.day) + ' at '
    elif time > next_week and time.year == now.year:
        pretty_prefix = '%B %-d' + pretty_suffix(time.day) + ' at '
    elif time > next_week:
        pretty_prefix = '%B %-d' + pretty_suffix(time.day) + ' %Y at '

    return time.strftime(pretty_prefix + pretty_fmt) 
Example 24
Project: mlbv   Author: kmac   File: mlbgamedata.py    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 25
Project: mlbv   Author: kmac   File: standings.py    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 26
Project: mlbv   Author: kmac   File: standings.py    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 27
Project: mlbv   Author: kmac   File: util.py    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 28
Project: pyblish-win   Author: pyblish   File: imaplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _mesg(self, s, secs=None):
            if secs is None:
                secs = time.time()
            tm = time.strftime('%M:%S', time.localtime(secs))
            sys.stderr.write('  %s.%02d %s\n' % (tm, (secs*100)%100, s))
            sys.stderr.flush() 
Example 29
Project: pyblish-win   Author: pyblish   File: imaplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def Time2Internaldate(date_time):

    """Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time (as returned by time.localtime()), or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    """

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
    if dt[0] == '0':
        dt = ' ' + dt[1:]
    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"' 
Example 30
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            Utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            Utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsedate_acceptable_to_time_functions(self):
        eq = self.assertEqual
        timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup)), 2003)
        timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup[:9]))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup[:9])), 2003) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        fp = openfile('PyBanner048.gif')
        try:
            data = fp.read()
        finally:
            fp.close()

        container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
        image = MIMEImage(data, name='dingusfish.gif')
        image.add_header('content-disposition', 'attachment',
                         filename='dingusfish.gif')
        intro = MIMEText('''\
Hi there,

This is the dingus fish.
''')
        container.attach(intro)
        container.attach(image)
        container['From'] = 'Barry <barry@digicool.com>'
        container['To'] = 'Dingus Lovers <cravindogs@cravindogs.com>'
        container['Subject'] = 'Here is your dingus fish'

        now = 987809702.54848599
        timetuple = time.localtime(now)
        if timetuple[-1] == 0:
            tzsecs = time.timezone
        else:
            tzsecs = time.altzone
        if tzsecs > 0:
            sign = '-'
        else:
            sign = '+'
        tzoffset = ' %s%04d' % (sign, tzsecs // 36)
        container['Date'] = time.strftime(
            '%a, %d %b %Y %H:%M:%S',
            time.localtime(now)) + tzoffset
        self._msg = container
        self._im = image
        self._txt = intro 
Example 33
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsedate_acceptable_to_time_functions(self):
        eq = self.assertEqual
        timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup)), 2003)
        timetup = utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup[:9]))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup[:9])), 2003) 
Example 35
Project: pyblish-win   Author: pyblish   File: _strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __calc_am_pm(self):
        # Set self.am_pm by using time.strftime().

        # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
        # magical; just happened to have used it everywhere else where a
        # static date was needed.
        am_pm = []
        for hour in (01,22):
            time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
            am_pm.append(time.strftime("%p", time_tuple).lower()) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def compare_against_time(self, testing, directive, tuple_position,
                             error_msg):
        """Helper method that tests testing against directive based on the
        tuple_position of time_tuple.  Uses error_msg as error message.

        """
        strftime_output = time.strftime(directive, self.time_tuple).lower()
        comparison = testing[self.time_tuple[tuple_position]]
        self.assertIn(strftime_output, testing,
                      "%s: not found in tuple" % error_msg)
        self.assertEqual(comparison, strftime_output,
                         "%s: position within tuple incorrect; %s != %s" %
                         (error_msg, comparison, strftime_output)) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_am_pm(self):
        # Make sure AM/PM representation done properly
        strftime_output = time.strftime("%p", self.time_tuple).lower()
        self.assertIn(strftime_output, self.LT_ins.am_pm,
                      "AM/PM representation not in tuple")
        if self.time_tuple[3] < 12: position = 0
        else: position = 1
        self.assertEqual(self.LT_ins.am_pm[position], strftime_output,
                         "AM/PM representation in the wrong position within the tuple") 
Example 38
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_timezone(self):
        # Make sure timezone is correct
        timezone = time.strftime("%Z", self.time_tuple).lower()
        if timezone:
            self.assertTrue(timezone in self.LT_ins.timezone[0] or
                            timezone in self.LT_ins.timezone[1],
                            "timezone %s not found in %s" %
                            (timezone, self.LT_ins.timezone)) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def helper(self, directive, position):
        """Helper fxn in testing."""
        strf_output = time.strftime("%" + directive, self.time_tuple)
        strp_output = _strptime._strptime_time(strf_output, "%" + directive)
        self.assertTrue(strp_output[position] == self.time_tuple[position],
                        "testing of '%s' directive failed; '%s' -> %s != %s" %
                         (directive, strf_output, strp_output[position],
                          self.time_tuple[position])) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_hour(self):
        # Test hour directives
        self.helper('H', 3)
        strf_output = time.strftime("%I %p", self.time_tuple)
        strp_output = _strptime._strptime_time(strf_output, "%I %p")
        self.assertTrue(strp_output[3] == self.time_tuple[3],
                        "testing of '%%I %%p' directive failed; '%s' -> %s != %s" %
                         (strf_output, strp_output[3], self.time_tuple[3])) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_percent(self):
        # Make sure % signs are handled properly
        strf_output = time.strftime("%m %% %Y", self.time_tuple)
        strp_output = _strptime._strptime_time(strf_output, "%m %% %Y")
        self.assertTrue(strp_output[0] == self.time_tuple[0] and
                         strp_output[1] == self.time_tuple[1],
                        "handling of percent sign failed") 
Example 42
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_caseinsensitive(self):
        # Should handle names case-insensitively.
        strf_output = time.strftime("%B", self.time_tuple)
        self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"),
                        "strptime does not handle ALL-CAPS names properly")
        self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"),
                        "strptime does not handle lowercase names properly")
        self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"),
                        "strptime does not handle capword names properly") 
Example 43
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_gregorian_calculation(self):
        # Test that Gregorian date can be calculated from Julian day
        format_string = "%Y %H %M %S %w %j %Z"
        result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
                                    format_string)
        self.assertTrue(result.tm_year == self.time_tuple.tm_year and
                         result.tm_mon == self.time_tuple.tm_mon and
                         result.tm_mday == self.time_tuple.tm_mday,
                        "Calculation of Gregorian date failed;"
                         "%s-%s-%s != %s-%s-%s" %
                         (result.tm_year, result.tm_mon, result.tm_mday,
                          self.time_tuple.tm_year, self.time_tuple.tm_mon,
                          self.time_tuple.tm_mday)) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_day_of_week_calculation(self):
        # Test that the day of the week is calculated as needed
        format_string = "%Y %m %d %H %S %j %Z"
        result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
                                    format_string)
        self.assertTrue(result.tm_wday == self.time_tuple.tm_wday,
                        "Calculation of day of the week failed;"
                         "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_week_of_year_and_day_of_week_calculation(self):
        # Should be able to infer date if given year, week of year (%U or %W)
        # and day of the week
        def test_helper(ymd_tuple, test_reason):
            for directive in ('W', 'U'):
                format_string = "%%Y %%%s %%w" % directive
                dt_date = datetime_date(*ymd_tuple)
                strp_input = dt_date.strftime(format_string)
                strp_output = _strptime._strptime_time(strp_input, format_string)
                self.assertTrue(strp_output[:3] == ymd_tuple,
                        "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" %
                            (test_reason, directive, strp_input,
                                strp_output[:3], ymd_tuple,
                                strp_output[7], dt_date.timetuple()[7]))
        test_helper((1901, 1, 3), "week 0")
        test_helper((1901, 1, 8), "common case")
        test_helper((1901, 1, 13), "day on Sunday")
        test_helper((1901, 1, 14), "day on Monday")
        test_helper((1905, 1, 1), "Jan 1 on Sunday")
        test_helper((1906, 1, 1), "Jan 1 on Monday")
        test_helper((1906, 1, 7), "first Sunday in a year starting on Monday")
        test_helper((1905, 12, 31), "Dec 31 on Sunday")
        test_helper((1906, 12, 31), "Dec 31 on Monday")
        test_helper((2008, 12, 29), "Monday in the last week of the year")
        test_helper((2008, 12, 22), "Monday in the second-to-last week of the "
                                    "year")
        test_helper((1978, 10, 23), "randomly chosen date")
        test_helper((2004, 12, 18), "randomly chosen date")
        test_helper((1978, 10, 23), "year starting and ending on Monday while "
                                        "date not on Sunday or Monday")
        test_helper((1917, 12, 17), "year starting and ending on Monday with "
                                        "a Monday not at the beginning or end "
                                        "of the year")
        test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
                                        "ending on Monday")
        test_helper((2007, 01, 07), "First Sunday of 2007")
        test_helper((2007, 01, 14), "Second Sunday of 2007")
        test_helper((2006, 12, 31), "Last Sunday of 2006")
        test_helper((2006, 12, 24), "Second to last Sunday of 2006") 
Example 46
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_strptime(self):
        # Should be able to go round-trip from strftime to strptime without
        # raising an exception.
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = '%' + directive
            strf_output = time.strftime(format, tt)
            try:
                time.strptime(strf_output, format)
            except ValueError:
                self.fail("conversion specifier %r failed with '%s' input." %
                          (format, strf_output)) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def asn1time(cert_time):
    # Some versions of OpenSSL ignore seconds, see #18207
    # 0.9.8.i
    if ssl._OPENSSL_API_VERSION == (0, 9, 8, 9, 15):
        fmt = "%b %d %H:%M:%S %Y GMT"
        dt = datetime.datetime.strptime(cert_time, fmt)
        dt = dt.replace(second=0)
        cert_time = dt.strftime(fmt)
        # %d adds leading zero but ASN1_TIME_print() uses leading space
        if cert_time[4] == "0":
            cert_time = cert_time[:4] + " " + cert_time[5:]

    return cert_time

# Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2 
Example 48
Project: pyblish-win   Author: pyblish   File: test_ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cert_time_to_seconds(self):
        timestring = "Jan  5 09:34:43 2018 GMT"
        ts = 1515144883.0
        self.cert_time_ok(timestring, ts)
        # accept keyword parameter, assert its name
        self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts)
        # accept both %e and %d (space or zero generated by strftime)
        self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts)
        # case-insensitive
        self.cert_time_ok("JaN  5 09:34:43 2018 GmT", ts)
        self.cert_time_fail("Jan  5 09:34 2018 GMT")     # no seconds
        self.cert_time_fail("Jan  5 09:34:43 2018")      # no GMT
        self.cert_time_fail("Jan  5 09:34:43 2018 UTC")  # not GMT timezone
        self.cert_time_fail("Jan 35 09:34:43 2018 GMT")  # invalid day
        self.cert_time_fail("Jon  5 09:34:43 2018 GMT")  # invalid month
        self.cert_time_fail("Jan  5 24:00:00 2018 GMT")  # invalid hour
        self.cert_time_fail("Jan  5 09:60:43 2018 GMT")  # invalid minute

        newyear_ts = 1230768000.0
        # leap seconds
        self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts)
        # same timestamp
        self.cert_time_ok("Jan  1 00:00:00 2009 GMT", newyear_ts)

        self.cert_time_ok("Jan  5 09:34:59 2018 GMT", 1515144899)
        #  allow 60th second (even if it is not a leap second)
        self.cert_time_ok("Jan  5 09:34:60 2018 GMT", 1515144900)
        #  allow 2nd leap second for compatibility with time.strptime()
        self.cert_time_ok("Jan  5 09:34:61 2018 GMT", 1515144901)
        self.cert_time_fail("Jan  5 09:34:62 2018 GMT")  # invalid seconds

        # no special treatement for the special value:
        #   99991231235959Z (rfc 5280)
        self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cert_time_to_seconds_locale(self):
        # `cert_time_to_seconds()` should be locale independent

        def local_february_name():
            return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0))

        if local_february_name().lower() == 'feb':
            self.skipTest("locale-specific month name needs to be "
                          "different from C locale")

        # locale-independent
        self.cert_time_ok("Feb  9 00:00:00 2007 GMT", 1170979200.0)
        self.cert_time_fail(local_february_name() + "  9 00:00:00 2007 GMT") 
Example 50
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_time(self):
        d = 1181399930.036952
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) 
Example 51
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        log_str = '%s - - [%s] "%s %s %s" %s %s %s %s\n' % (self.ip_addr,
                     time.strftime("%d/%b/%Y:%H:%M:%S %z", time.gmtime()),
                     self.request_method, self.request_uri or "-", self.request_protocol,
                     self.status.split()[0] if self.status else "0",
                     self.resp_content_length or 0,
                     get_value(self.req_headers, "referer","-"),
                     get_value(self.req_headers, "user-agent", "-") or "-")
        return log_str 
Example 52
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_mult_thread.py    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()) 
Example 53
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_faster.py    Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    :param name:
    :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()) 
Example 54
Project: iSDX   Author: sdn-ixp   File: gauge.py    Apache License 2.0 5 votes vote down vote up
def update(self, rcv_time, msg):
        # TODO: it may be worth while verifying this is the correct stats
        # response before doing this
        self.reply_pending = False
        rcv_time_str = time.strftime('%b %d %H:%M:%S')

        for stat in msg.body:
            if stat.port_no == msg.datapath.ofproto.OFPP_CONTROLLER:
                ref = self.dp.name + "-CONTROLLER"
            elif stat.port_no == msg.datapath.ofproto.OFPP_LOCAL:
                ref = self.dp.name + "-LOCAL"
            elif stat.port_no not in self.dp.ports:
                self.logger.info("stats for unknown port %s", stat.port_no)
                continue
            else:
                ref = self.dp.name + "-" + self.dp.ports[stat.port_no].name

            with open(self.logfile, 'a') as logfile:
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-packets-out",
                                                       stat.tx_packets))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-packets-in",
                                                       stat.rx_packets))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-bytes-out",
                                                       stat.tx_bytes))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-bytes-in",
                                                       stat.rx_bytes))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-dropped-out",
                                                       stat.tx_dropped))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-dropped-in",
                                                       stat.rx_dropped))
                logfile.write('{0}\t{1}\t{2}\n'.format(rcv_time_str,
                                                       ref + "-errors-in",
                                                       stat.rx_errors)) 
Example 55
Project: iSDX   Author: sdn-ixp   File: gauge.py    Apache License 2.0 5 votes vote down vote up
def update(self, rcv_time, msg):
        # TODO: it may be worth while verifying this is the correct stats
        # response before doing this
        self.reply_pending = False
        jsondict = msg.to_jsondict()
        rcv_time_str = time.strftime('%b %d %H:%M:%S')

        with open(self.logfile, 'a') as logfile:
            ref = self.dp.name + "-flowtables"
            logfile.write("---\n")
            logfile.write("time: {0}\nref: {1}\nmsg: {2}\n".format(
                rcv_time_str, ref, json.dumps(jsondict, indent=4))) 
Example 56
Project: zmirror   Author: aploium   File: _logtime.py    MIT License 5 votes vote down vote up
def logtime(is_print_date=False, timesep=':', datesep='-'):
    from time import time, localtime, strftime
    _localtime = localtime(time())
    _dateformat = '%Y' + datesep + '%m' + datesep + '%d'
    _timeformat = '%H' + timesep + '%M' + timesep + '%S'
    if is_print_date:
        return strftime(_dateformat + " " + _timeformat, _localtime)
    else:
        return strftime(_timeformat, _localtime) 
Example 57
Project: cloudlog   Author: navoshta   File: cloudlog.py    MIT License 5 votes vote down vote up
def add_plot(self, notify=False, caption=None):
        """
        Saves current `pyplot` plot as a .png, uploads it to Dropbox and optionally notifies via Telegram chat.

        Parameters
        ----------
        notify  :
                  Flag indicating if we need to send a Telegram notification.
        caption :
                  Optional plot caption.
        """
        plot_file = time.strftime('%Y-%m-%d_%H-%M-%S') + '.png'
        plot_path = os.path.join(self.root, plot_file)
        pyplot.savefig(plot_path)

        self.cloud_upload_plot(plot_file)
        if notify:
            self.bot_send_plot(plot_file, caption) 
Example 58
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def time_string():
    ISOTIMEFORMAT = '%Y-%m-%d %X'
    string = '[{}]'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
    return string 
Example 59
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def createNewDir(BASE_FOLDER):
    parquet_dir = os.path.join(BASE_FOLDER, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    os.makedirs(parquet_dir)
    return parquet_dir 
Example 60
Project: neural-fingerprinting   Author: StephanZheng   File: master.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _show_status_for_work(self, work):
    """Shows status for given work pieces.

    Args:
      work: instance of either AttackWorkPieces or DefenseWorkPieces
    """
    work_count = len(work.work)
    work_completed = {}
    work_completed_count = 0
    for v in itervalues(work.work):
      if v['is_completed']:
        work_completed_count += 1
        worker_id = v['claimed_worker_id']
        if worker_id not in work_completed:
          work_completed[worker_id] = {
              'completed_count': 0,
              'last_update': 0.0,
          }
        work_completed[worker_id]['completed_count'] += 1
        work_completed[worker_id]['last_update'] = max(
            work_completed[worker_id]['last_update'],
            v['claimed_worker_start_time'])
    print('Completed {0}/{1} work'.format(work_completed_count,
                                          work_count))
    for k in sorted(iterkeys(work_completed)):
      last_update_time = time.strftime(
          '%Y-%m-%d %H:%M:%S',
          time.localtime(work_completed[k]['last_update']))
      print('Worker {0}: completed {1}   last claimed work at {2}'.format(
          k, work_completed[k]['completed_count'], last_update_time)) 
Example 61
Project: radonreader   Author: ceandre   File: radon_reader_old_v2.py    GNU General Public License v3.0 5 votes vote down vote up
def GetRadonValue():
    if args.verbose and not args.silent:
        print ("Connecting...")
    DevBT = btle.Peripheral(args.address.upper(), "random")
    RadonEye = btle.UUID("00001523-1212-efde-1523-785feabcd123")
    RadonEyeService = DevBT.getServiceByUUID(RadonEye)

    # Write 0x50 to 00001524-1212-efde-1523-785feabcd123
    if args.verbose and not args.silent:
        print ("Writing...")
    uuidWrite  = btle.UUID("00001524-1212-efde-1523-785feabcd123")
    RadonEyeWrite = RadonEyeService.getCharacteristics(uuidWrite)[0]
    RadonEyeWrite.write(bytes("\x50"))

    # Read from 3rd to 6th byte of 00001525-1212-efde-1523-785feabcd123
    if args.verbose and not args.silent:
        print ("Reading...")
    uuidRead  = btle.UUID("00001525-1212-efde-1523-785feabcd123")
    RadonEyeValue = RadonEyeService.getCharacteristics(uuidRead)[0]
    RadonValue = RadonEyeValue.read()
    RadonValue = struct.unpack('<f',RadonValue[2:6])[0]
   
    if args.becquerel:
        Unit="Bq/m^3"
        RadonValue = ( RadonValue * 37 )
    else:
        Unit="pCi/L"
 
    if args.silent:
        print ("%0.2f" % (RadonValue))
    else: 
        print ("%s - %s - Radon Value: %0.2f %s" % (time.strftime("%Y-%m-%d [%H:%M:%S]"),args.address.upper(),RadonValue,Unit)) 
Example 62
Project: radonreader   Author: ceandre   File: radon_reader_old_v1.py    GNU General Public License v3.0 5 votes vote down vote up
def GetRadonValue():
    if Verbose: 
        print ("Connecting...")
    DevBT = btle.Peripheral(RadonEyeBTAddress, "random")
    RadonEye = btle.UUID("00001523-1212-efde-1523-785feabcd123")
    RadonEyeService = DevBT.getServiceByUUID(RadonEye)

    # Write 0x50 to 00001524-1212-efde-1523-785feabcd123
    if Verbose: 
        print ("Writing...")
    uuidWrite  = btle.UUID("00001524-1212-efde-1523-785feabcd123")
    RadonEyeWrite = RadonEyeService.getCharacteristics(uuidWrite)[0]
    RadonEyeWrite.write(bytes("\x50"))

    # Read from 3rd to 6th byte of 00001525-1212-efde-1523-785feabcd123
    if Verbose: 
        print ("Reading...")
    uuidRead  = btle.UUID("00001525-1212-efde-1523-785feabcd123")
    RadonEyeValue = RadonEyeService.getCharacteristics(uuidRead)[0]
    RadonValue = RadonEyeValue.read()
    RadonValue = struct.unpack('<f',RadonValue[2:6])[0]
   
    if picoCurie:
        Unit="pCi/L"
    else:
        Unit="Bq/m^3"
        RadonValue = RadonValue * 37
 
    if OnlyValue:
        print ("%0.2f" % (RadonValue))
    else: 
        print ("%s - Radon Value: %0.2f %s" % (time.strftime("%Y-%m-%d [%H:%M:%S]"),RadonValue,Unit)) 
Example 63
Project: py_messenger   Author: cody-rocker   File: message.py    GNU General Public License v2.0 5 votes vote down vote up
def _time_stamp(self):
        return strftime('%b %d %Y, %-I:%M %p') 
Example 64
Project: py_messenger   Author: cody-rocker   File: py_sms.py    GNU General Public License v2.0 5 votes vote down vote up
def time_stamp():
    return strftime('%-I:%M %p - %b %d %Y') 
Example 65
Project: MusicDownloader   Author: wwwpf   File: play_manager.py    GNU General Public License v3.0 5 votes vote down vote up
def update_duration_info(self, current_info):
        s = time.strftime("%M:%S", time.gmtime(current_info))
        t = "%s / %s" % (s, self.song.get_time())
        self.duration_label.setText(t) 
Example 66
Project: MusicDownloader   Author: wwwpf   File: song_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_time(self):
        return time.strftime("%M:%S", time.gmtime(int(self.duration / 1000))) 
Example 67
Project: MusicDownloader   Author: wwwpf   File: download_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_remain_time(self):
        if self.speed < 1e-6 or self.file_size is math.inf:
            return "--:--"
        if not self.finished():
            t = (self.file_size - self.current_size) / self.speed
            return time.strftime("%M:%S", time.gmtime(t))
        return "已完成" 
Example 68
Project: gluster-integration   Author: Tendrl   File: callback.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def georep_checkpoint_completed(self, event):
        georep_pair = "{0}:{1}:{2}--->{3}:{4}".format(
            event['message']["master_node"],
            event['message']["master_volume"],
            event['message']["brick_path"],
            event['message']["slave_host"],
            event['message']["slave_volume"]
        )
        context = "georep_checkpoint_completed|" + georep_pair
        cp_creation_time = time.localtime(
            float(event['message']['checkpoint_time'])
        )
        cp_creation_time = time.strftime("%d %b %Y %H:%M:%S", cp_creation_time)
        cp_completion_time = time.localtime(
            float(event['message']['checkpoint_completion_time'])
        )
        cp_completion_time = time.strftime(
            "%d %b %Y %H:%M:%S",
            cp_completion_time
        )

        message = "Georeplication checkpoint completed for pair {0}." \
                  " Check point creation time {1}." \
                  " Check point completion time {2}. in cluster {3}".format(
                      georep_pair,
                      cp_creation_time,
                      cp_completion_time,
                      self.cluster_short_name
                  )
        native_event = NS.gluster.objects.NativeEvents(
            context,
            message=message,
            severity="info",
            current_value="georep_checkpoint_completed",
            alert_notify=True
        )
        native_event.save() 
Example 69
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result 
Example 70
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: heuristics.py    MIT License 5 votes vote down vote up
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))} 
Example 71
Project: pyblish-win   Author: pyblish   File: pygettext.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def write(self, fp):
        options = self.__options
        timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
        # The time stamp in the header doesn't have the same format as that
        # generated by xgettext...
        print >> fp, pot_header % {'time': timestamp, 'version': __version__}
        # Sort the entries.  First sort each particular entry's keys, then
        # sort all the entries by their first item.
        reverse = {}
        for k, v in self.__messages.items():
            keys = v.keys()
            keys.sort()
            reverse.setdefault(tuple(keys), []).append((k, v))
        rkeys = reverse.keys()
        rkeys.sort()
        for rkey in rkeys:
            rentries = reverse[rkey]
            rentries.sort()
            for k, v in rentries:
                isdocstring = 0
                # If the entry was gleaned out of a docstring, then add a
                # comment stating so.  This is to aid translators who may wish
                # to skip translating some unimportant docstrings.
                if reduce(operator.__add__, v.values()):
                    isdocstring = 1
                # k is the message string, v is a dictionary-set of (filename,
                # lineno) tuples.  We want to sort the entries in v first by
                # file name and then by line number.
                v = v.keys()
                v.sort()
                if not options.writelocations:
                    pass
                # location comments are different b/w Solaris and GNU:
                elif options.locationstyle == options.SOLARIS:
                    for filename, lineno in v:
                        d = {'filename': filename, 'lineno': lineno}
                        print >>fp, _(
                            '# File: %(filename)s, line: %(lineno)d') % d
                elif options.locationstyle == options.GNU:
                    # fit as many locations on one line, as long as the
                    # resulting line length doesn't exceeds 'options.width'
                    locline = '#:'
                    for filename, lineno in v:
                        d = {'filename': filename, 'lineno': lineno}
                        s = _(' %(filename)s:%(lineno)d') % d
                        if len(locline) + len(s) <= options.width:
                            locline = locline + s
                        else:
                            print >> fp, locline
                            locline = "#:" + s
                    if len(locline) > 2:
                        print >> fp, locline
                if isdocstring:
                    print >> fp, '#, docstring'
                print >> fp, 'msgid', normalize(k)
                print >> fp, 'msgstr ""\n' 
Example 72
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def formatdate(timeval=None, localtime=False, usegmt=False):
    """Returns a date string as specified by RFC 2822, e.g.:

    Fri, 09 Nov 2001 01:08:47 -0000

    Optional timeval if given is a floating point time value as accepted by
    gmtime() and localtime(), otherwise the current time is used.

    Optional localtime is a flag that when True, interprets timeval, and
    returns a date relative to the local timezone instead of UTC, properly
    taking daylight savings time into account.

    Optional argument usegmt means that the timezone is written out as
    an ascii string, not numeric one (so "GMT" instead of "+0000"). This
    is needed for HTTP, and is only used when localtime==False.
    """
    # Note: we cannot use strftime() because that honors the locale and RFC
    # 2822 requires that day and month names be the English abbreviations.
    if timeval is None:
        timeval = time.time()
    if localtime:
        now = time.localtime(timeval)
        # Calculate timezone offset, based on whether the local zone has
        # daylight savings time, and whether DST is in effect.
        if time.daylight and now[-1]:
            offset = time.altzone
        else:
            offset = time.timezone
        hours, minutes = divmod(abs(offset), 3600)
        # Remember offset is in seconds west of UTC, but the timezone is in
        # minutes east of UTC, so the signs differ.
        if offset > 0:
            sign = '-'
        else:
            sign = '+'
        zone = '%s%02d%02d' % (sign, hours, minutes // 60)
    else:
        now = time.gmtime(timeval)
        # Timezone offset is always -0000
        if usegmt:
            zone = 'GMT'
        else:
            zone = '-0000'
    return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
        ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
        now[2],
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
        now[0], now[3], now[4], now[5],
        zone) 
Example 73
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def doRollover(self):
        """
        do a rollover; in this case, a date/time stamp is appended to the filename
        when the rollover happens.  However, you want the file to be named for the
        start of the interval, not the current time.  If there is a backup count,
        then we have to get a list of matching filenames, sort them and remove
        the one with the oldest suffix.
        """
        if self.stream:
            self.stream.close()
            self.stream = None
        # get the time that this sequence started at and make it a TimeTuple
        currentTime = int(time.time())
        dstNow = time.localtime(currentTime)[-1]
        t = self.rolloverAt - self.interval
        if self.utc:
            timeTuple = time.gmtime(t)
        else:
            timeTuple = time.localtime(t)
            dstThen = timeTuple[-1]
            if dstNow != dstThen:
                if dstNow:
                    addend = 3600
                else:
                    addend = -3600
                timeTuple = time.localtime(t + addend)
        dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
        if os.path.exists(dfn):
            os.remove(dfn)
        # Issue 18940: A file may not have been created if delay is True.
        if os.path.exists(self.baseFilename):
            os.rename(self.baseFilename, dfn)
        if self.backupCount > 0:
            for s in self.getFilesToDelete():
                os.remove(s)
        if not self.delay:
            self.stream = self._open()
        newRolloverAt = self.computeRollover(currentTime)
        while newRolloverAt <= currentTime:
            newRolloverAt = newRolloverAt + self.interval
        #If DST changes and midnight or weekly rollover, adjust for this.
        if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
            dstAtRollover = time.localtime(newRolloverAt)[-1]
            if dstNow != dstAtRollover:
                if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
                    addend = -3600
                else:           # DST bows out before next rollover, so we need to add an hour
                    addend = 3600
                newRolloverAt += addend
        self.rolloverAt = newRolloverAt 
Example 74
Project: pyblish-win   Author: pyblish   File: urllib.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        import mimetools
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError, ('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            data = base64.decodestring(data)
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        f = StringIO(msg)
        headers = mimetools.Message(f, 0)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example 75
Project: pyblish-win   Author: pyblish   File: _strptime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def __calc_date_time(self):
        # Set self.date_time, self.date, & self.time by using
        # time.strftime().

        # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
        # overloaded numbers is minimized.  The order in which searches for
        # values within the format string is very important; it eliminates
        # possible ambiguity for what something represents.
        time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
        date_time = [None, None, None]
        date_time[0] = time.strftime("%c", time_tuple).lower()
        date_time[1] = time.strftime("%x", time_tuple).lower()
        date_time[2] = time.strftime("%X", time_tuple).lower()
        replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
                    (self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
                    (self.a_month[3], '%b'), (self.am_pm[1], '%p'),
                    ('1999', '%Y'), ('99', '%y'), ('22', '%H'),
                    ('44', '%M'), ('55', '%S'), ('76', '%j'),
                    ('17', '%d'), ('03', '%m'), ('3', '%m'),
                    # '3' needed for when no leading zero.
                    ('2', '%w'), ('10', '%I')]
        replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
                                                for tz in tz_values])
        for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
            current_format = date_time[offset]
            for old, new in replacement_pairs:
                # Must deal with possible lack of locale info
                # manifesting itself as the empty string (e.g., Swedish's
                # lack of AM/PM info) or a platform returning a tuple of empty
                # strings (e.g., MacOS 9 having timezone as ('','')).
                if old:
                    current_format = current_format.replace(old, new)
            # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
            # 2005-01-03 occurs before the first Monday of the year.  Otherwise
            # %U is used.
            time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
            if '00' in time.strftime(directive, time_tuple):
                U_W = '%W'
            else:
                U_W = '%U'
            date_time[offset] = current_format.replace('11', U_W)
        self.LC_date_time = date_time[0]
        self.LC_date = date_time[1]
        self.LC_time = date_time[2] 
Example 76
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test():
    """List info of all currently running processes emulating ps aux
    output.
    """
    import datetime

    today_day = datetime.date.today()
    templ = "%-10s %5s %4s %4s %7s %7s %-13s %5s %7s  %s"
    attrs = ['pid', 'cpu_percent', 'memory_percent', 'name', 'cpu_times',
             'create_time', 'memory_info']
    if _POSIX:
        attrs.append('uids')
        attrs.append('terminal')
    print(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY",
                   "START", "TIME", "COMMAND"))
    for p in process_iter():
        try:
            pinfo = p.as_dict(attrs, ad_value='')
        except NoSuchProcess:
            pass
        else:
            if pinfo['create_time']:
                ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
                if ctime.date() == today_day:
                    ctime = ctime.strftime("%H:%M")
                else:
                    ctime = ctime.strftime("%b%d")
            else:
                ctime = ''
            cputime = time.strftime("%M:%S",
                                    time.localtime(sum(pinfo['cpu_times'])))
            try:
                user = p.username()
            except Error:
                user = ''
            if _WINDOWS and '\\' in user:
                user = user.split('\\')[1]
            vms = pinfo['memory_info'] and \
                int(pinfo['memory_info'].vms / 1024) or '?'
            rss = pinfo['memory_info'] and \
                int(pinfo['memory_info'].rss / 1024) or '?'
            memp = pinfo['memory_percent'] and \
                round(pinfo['memory_percent'], 1) or '?'
            print(templ % (
                user[:10],
                pinfo['pid'],
                pinfo['cpu_percent'],
                memp,
                vms,
                rss,
                pinfo.get('terminal', '') or '?',
                ctime,
                cputime,
                pinfo['name'].strip() or '?')) 
Example 77
Project: pyblish-win   Author: pyblish   File: test_strftime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def strftest2(self, now):
        nowsecs = str(long(now))[:-1]
        now = self.now

        nonstandard_expectations = (
        # These are standard but don't have predictable output
            ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'),
            ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)),
            '%m/%d/%y %H:%M:%S'),
            ('%Z', '%s' % self.tz, 'time zone name'),

            # These are some platform specific extensions
            ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'),
            ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'),
            ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'),
            ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'),
            ('%n', '\n', 'newline character'),
            ('%r', '%02d:%02d:%02d %s' % (self.clock12, now[4], now[5], self.ampm),
            '%I:%M:%S %p'),
            ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'),
            ('%s', nowsecs, 'seconds since the Epoch in UCT'),
            ('%t', '\t', 'tab character'),
            ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'),
            ('%3y', '%03d' % (now[0]%100),
            'year without century rendered using fieldwidth'),
        )

        for e in nonstandard_expectations:
            try:
                result = time.strftime(e[0], now)
            except ValueError, result:
                msg = "Error for nonstandard '%s' format (%s): %s" % \
                      (e[0], e[2], str(result))
                if test_support.verbose:
                    print msg
                continue

            if re.match(escapestr(e[1], self.ampm), result):
                if test_support.verbose:
                    print "Supports nonstandard '%s' format (%s)" % (e[0], e[2])
            elif not result or result[0] == '%':
                if test_support.verbose:
                    print "Does not appear to support '%s' format (%s)" % \
                           (e[0], e[2])
            else:
                if test_support.verbose:
                    print "Conflict for nonstandard '%s' format (%s):" % \
                           (e[0], e[2])
                    print "  Expected %s, but got %s" % (e[1], result) 
Example 78
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_strftime_bounds_checking(self):
        # Make sure that strftime() checks the bounds of the various parts
        #of the time tuple (0 is valid for *all* values).

        # Check year [1900, max(int)]
        self.assertRaises(ValueError, time.strftime, '',
                            (1899, 1, 1, 0, 0, 0, 0, 1, -1))
        if time.accept2dyear:
            self.assertRaises(ValueError, time.strftime, '',
                                (-1, 1, 1, 0, 0, 0, 0, 1, -1))
            self.assertRaises(ValueError, time.strftime, '',
                                (100, 1, 1, 0, 0, 0, 0, 1, -1))
        # Check month [1, 12] + zero support
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, -1, 1, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 13, 1, 0, 0, 0, 0, 1, -1))
        # Check day of month [1, 31] + zero support
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, -1, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 32, 0, 0, 0, 0, 1, -1))
        # Check hour [0, 23]
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, -1, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 24, 0, 0, 0, 1, -1))
        # Check minute [0, 59]
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, -1, 0, 0, 1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 60, 0, 0, 1, -1))
        # Check second [0, 61]
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, -1, 0, 1, -1))
        # C99 only requires allowing for one leap second, but Python's docs say
        # allow two leap seconds (0..61)
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 62, 0, 1, -1))
        # No check for upper-bound day of week;
        #  value forced into range by a ``% 7`` calculation.
        # Start check at -2 since gettmarg() increments value before taking
        #  modulo.
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 0, -2, 1, -1))
        # Check day of the year [1, 366] + zero support
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 0, 0, -1, -1))
        self.assertRaises(ValueError, time.strftime, '',
                            (1900, 1, 1, 0, 0, 0, 0, 367, -1)) 
Example 79
Project: gamereporter   Author: gamesbook   File: report_builder.py    MIT License 4 votes vote down vote up
def save_games(self, style='full'):
        """
        Primary routine to drive creation of a reportlab PDF.

        Elements such as paragraphs & tables are collated in a list; and then
        the document is created.

        Headers and Footer are set via the doc.build().
        """
        elements = []
        if style in ['summary', 'compact']:
            elements.append(Spacer(1, 0.5*cm))
        # All done!
        if style in ['full', 'compact', 'summary']:
            # Create table per game
            for number, game in enumerate(self.games):
                if style == 'full':
                    gtable = self.create_table(game)
                    header = Paragraph('<b>%s</b>' % game.name,
                                       self.styles['CentreHeader'])
                    header.keepWithNext = True
                    elements.append(header)
                    elements.append(gtable)
                elif style == 'compact':
                    gtable = self.create_table_compact(game)
                    elements.append(gtable)
                elif style == 'summary':
                    gtable = self.create_table_summary(game, number)
                    elements.append(gtable)
            # After tables
            elements.append(Spacer(1, 0.5*cm))
            if self.time == 'US':
                _date = time.strftime("%b %d, %Y %H:%M")
            else:
                _date = time.strftime("%Y-%m-%d %H:%M")
            p2 = Paragraph('Printed at %s' % _date, self.styles['right'])
            elements.append(p2)
            if self.progress:
                print "Generating PDF Document... ... ..."
            self.doc.build(
                elements,
                onFirstPage=self.set_header_footer,
                onLaterPages=self.set_header_footer)
        elif style == 'excel':
            print "Generating XLS Spreadsheet ... ..."
            self.create_xls()
        elif style == 'json':
            print "Generating a JSON File ... ... ..."
            self.create_json()
        else:
            print 'The style "%s" does not exist!' % style
            sys.exit(1) 
Example 80
Project: adblock_host_generator   Author: ShadySquirrel   File: generate_adblock_urls.py    Apache License 2.0 4 votes vote down vote up
def push_to_git():
	logger.info("Starting git push")
	# initialize git via sh module. Smart, eh?
	git = sh.git.bake(_cwd=os.getcwd())
	msg = "* Initialized git in %s" % os.getcwd()
	print(msg)
	logging.debug(msg)


	# generate commit msg
	commit_date = time.strftime("%d.%m.%Y")
	commit_time = time.strftime("%H:%M:%S")
	commit_msg = "HOSTS: %s update (at %s)" % (commit_date, commit_time)
	print("* Generated commit message: %s" % commit_msg)
	logging.debug("* Commit message: %s", commit_msg)

	# get remote url
	print("* Generating git url")
	remote = git.remote().strip()
	remote_url = git.remote("get-url", remote, "--push")
	logging.debug("* git push url: %s", remote_url)

	# we'll need this later.
	url = remote_url

	# grab username and password from config
	from git_config import git_config

	# if git is using https instead of ssh, generate push url.
	if git_config["https"]:
		print("* Using HTTPS. Generating push url...")
		tmp = remote_url.split("//")
		login_data = "%s:%s" % (git_config["username"], git_config["password"])
		url = "%s//%s@%s" % (tmp[0].strip(), login_data, tmp[1].strip()) # no need for ':', it's left there from spliting.

		# add changes
		git.add(TARGET_FILE)
		print("* Adding changes..")
		logger.debug("* adding changes to git commit")

		# commit changes
		git.commit(m=commit_msg)
		print("* Commiting changes...")
		logger.debug("* commiting...")

		# push changes
		if not no_push:
			print("* Pushing changes...")
			logger.debug("* pushing changes.")
			git.push(url)
		else:
			print("* Commit created, to publish it, use 'git push' from your terminal")
			logger.debug("* commit is created, but not pushed. push  manually please")

		print("* Done!")

# generates banner placed on top of generated hosts file