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

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

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

github sungju / pycrashext / hangcheck.py View on Github external
def parse_task_info(line):
    try:
        idx = line.index("]")
    except:
        idx = -1

    if idx == -1:
        return None, None
    run_time = line[1:idx].strip()
    days_str, time_str = run_time.split()
    dto = datetime.strptime(time_str, "%H:%M:%S.%f")

    date_info = (int(days_str), dto.hour, dto.minute, dto.second, dto.microsecond)
    return date_info, line[idx + 1:]
github AaronTraas / Clash-Royale-Clan-Tools / crtools / memberfactory.py View on Github external
def enrich_member_with_history(self, member, historical_member):
        days_from_donation_reset = self.days_from_donation_reset

        member.join_date = historical_member['join_date']
        member.last_activity_date = historical_member['last_activity_date']
        member.last_donation_date = historical_member['last_donation_date']
        member.donations_last_week = historical_member['donations_last_week']
        member.days_inactive = (self.now - datetime.fromtimestamp(member.last_activity_date)).days
        member.days_inactive = member.days_inactive if member.days_inactive >= 0 else 0

        if member.last_seen:
            last_seen = datetime.strptime(member.last_seen.split('.')[0], '%Y%m%dT%H%M%S')
        else:
            last_seen = config['crtools']['timestamp']

        member.last_seen_formatted = last_seen.strftime('%c')

        last_seen_delta = self.now - last_seen
        member.last_seen_delta = ''
        if last_seen_delta.days >= 1:
            member.last_seen_delta = '{} {}, '.format(last_seen_delta.days, self.config['strings']['labelDays'])
        hours = round(last_seen_delta.seconds/3600)
        if hours < 1:
            member.last_seen_delta += '{} {}'.format(round(last_seen_delta.seconds/60), self.config['strings']['labelMinutes'])
        else:
            member.last_seen_delta += '{} {}'.format(hours, self.config['strings']['labelHours'])

        if member.join_date == 0:
github mozilla / build-tools / stage / post_upload.py View on Github external
def BuildIDToUnixTime(buildid):
    """Returns the timestamp the buildid represents in unix time."""
    try:
        pt = pytz.timezone('US/Pacific')
        return calendar.timegm(pt.localize(datetime.strptime(buildid, "%Y%m%d%H%M%S")).utctimetuple())
    except:
        raise "Could not parse buildid!"
github pimutils / khal / khal / ui / widgets.py View on Github external
def _get_current_value(self):
        try:
            new_date = datetime.strptime(self.get_edit_text(), self.dateformat).date()
        except ValueError:
            raise DateConversionError
        else:
            return new_date
github realpython / book2-exercises / web2py-rest / gluon / fileutils.py View on Github external
def parse_legacy(version="Version 1.99.0 (2011-09-19 08:23:26)"):
    """Parses "legacy" version string

    Args:
        version(str): the version string

    Returns:
        tuple: Major, Minor, Patch, Release, Build Date

    """
    re_version = re.compile('[^\d]+ (\d+)\.(\d+)\.(\d+)\s*\((?P.+?)\)\s*(?P[a-z]+)?')
    m = re_version.match(version)
    a, b, c = int(m.group(1)), int(m.group(2)), int(m.group(3)),
    pre_release = m.group('type') or 'dev'
    build = datetime.datetime.strptime(m.group('datetime'), '%Y-%m-%d %H:%M:%S')
    return (a, b, c, pre_release, build)
github AndrewIngram / django-extra-views / extra_views / contrib / mixins.py View on Github external
def try_convert_to_date(self, word):
        """
        Tries to convert word to date(datetime) using search_date_formats
        Return None if word fits no one format
        """
        for frm in self.search_date_formats:
            try:
                return datetime.datetime.strptime(word, frm).date()
            except ValueError:
                pass
        return None
github paul-reiners / udacity-intro-hadoop-mapreduce / code / project / map_reduce / response_time_reducer.py View on Github external
prefix_len = len('2012-02-22 21:36:17')
    date_format = '%Y-%m-%d %H:%M:%S'
    for line in reader:
        if len(line) == 4:
            the_id = line[0]
            if current_id is None or the_id != current_id:
                if not current_id is None:
                    write_record(current_id, min_minutes_diff, writer)
                    min_minutes_diff = None
                current_id = the_id

            node_type = line[2]
            added_at = line[3]
            if node_type == "question":
                question_added_at = \
                    datetime.strptime(added_at[:prefix_len], date_format)
            else:
                answer_added_at = \
                    datetime.strptime(added_at[:prefix_len], date_format)
                if not question_added_at is None:
                    delta = answer_added_at - question_added_at
                    minutes_diff = delta.seconds / 60
                    if min_minutes_diff is None or \
                        minutes_diff < min_minutes_diff:
                        min_minutes_diff = minutes_diff
    write_record(current_id, min_minutes_diff, writer)
github boland1992 / SeisSuite / build / lib.linux-x86_64-2.7 / seissuite / ant / psconfig.py View on Github external
self.CROSSCORR_STATIONS_SUBSET = \
        json.loads(self.CROSSCORR_STATIONS_SUBSET)
        
        # locations to skip
        self.CROSSCORR_SKIPLOCS = \
        json.loads(self.config.get('cross-correlation', 'CROSSCORR_SKIPLOCS'))
        
        #GET RID OF .day() for FIRSTDAY and LASTDAY variables. 
        #This is is to allow for the interval to be a datetime object rather than just
        #a date object!
        
        # first and last day, minimum data fill per day
        self.FIRSTDAY = self.config.get('cross-correlation', 'FIRSTDAY')
        self.FIRSTDAY = dt.datetime.strptime(self.FIRSTDAY, '%d/%m/%Y')
        self.LASTDAY = self.config.get('cross-correlation', 'LASTDAY')
        self.LASTDAY = dt.datetime.strptime(self.LASTDAY, '%d/%m/%Y')
        self.MINFILL = self.config.getfloat('cross-correlation', 'MINFILL')
        
        # band-pass parameters
        self.PERIODMIN = self.config.getfloat('cross-correlation', 
                                              'PERIODMIN')
        self.PERIODMAX = self.config.getfloat('cross-correlation', 
                                              'PERIODMAX')
        self.FREQMIN = 1.0 / self.PERIODMAX
        self.FREQMAX = 1.0 / self.PERIODMIN
        self.CORNERS = self.config.getint('cross-correlation', 'CORNERS')
        self.ZEROPHASE = self.config.getboolean('cross-correlation', 
                                                'ZEROPHASE')
        # resample period (to decimate traces, after band-pass)
        self.PERIOD_RESAMPLE = self.config.getfloat('cross-correlation', 
                                               'PERIOD_RESAMPLE')
github jbms / finance-dl / finance_dl / ultipro_google.py View on Github external
return table
            except:
                import traceback
                traceback.print_exc()

        table, = self.wait_and_return(get_statement_table)
        date_format = '%m/%d/%Y'
        for row in table.find_elements_by_xpath('tbody/tr'):
            row_text = [
                x.text.strip() for x in row.find_elements_by_tag_name('td')
            ]
            row_text = [x for x in row_text if x]
            pay_date = row_text[0]
            document_number = row_text[1]
            assert re.fullmatch('[0-9A-Z]+', document_number), document_number
            pay_date = datetime.datetime.strptime(pay_date, date_format).date()
            document_str = 'Document %r : %r' % (pay_date, document_number)
            if (pay_date, document_number) in existing_statements:
                logger.info('  Found in existing')
                continue
            if (pay_date, document_number) not in downloaded_statements:
                logger.info('%s:  Downloading', document_str)
                link = row.find_element_by_tag_name('a')
                link.click()
                download_link, = self.wait_and_return(
                    lambda: self.find_element_in_any_frame(
                        By.XPATH,
                        '//input[@type="image" and contains(@title, "download")]'
                    ))
                download_link.click()
                logger.info('%s: Waiting to get download', document_str)
                download_result, = self.wait_and_return(