Python time.strptime() Examples

The following are code examples for showing how to use time.strptime(). 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: mpesaviz   Author: savioabuga   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_records(self, uploaded_file, file_type):
            transactions = []
            for transaction in csv.DictReader(uploaded_file, delimiter=',',):

                # sent transactions
                if file_type == Transaction.TYPES.sent:
                    try:
                        date = time.strptime(transaction['Date'], '%d/%m/%Y %H:%M:%S')
                        date = datetime(*date[:6])
                        transactions.append(Transaction(code=transaction['Code'], date=date, recipient=transaction['Recipient'],
                                                        amount=float(transaction['Amount'].replace(",", "")), type=file_type, phonenumber=PhoneNumber.from_string(transaction['No.'], 'KE')))
                    except NumberParseException:
                        pass

                # received transactions
                if file_type == Transaction.TYPES.received:
                    try:
                        date = time.strptime(transaction['Date'], '%d/%m/%Y %H:%M:%S')
                        date = datetime(*date[:6])
                        transactions.append(Transaction(code=transaction['\xef\xbb\xbf"Code"'], date=date, sent_by=transaction['Sent By'],
                                                        amount=float(transaction['Amount'].replace(",", "")), type=file_type))
                    except NumberParseException:
                        pass

            Transaction.objects.bulk_create(transactions) 
Example 2
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 3
Project: oeffis-paper   Author: djaffry   File: api_oebb.py    MIT License 6 votes vote down vote up
def _extract_line_and_calc_countdown(connection):
        line = {
            # 'name': data['sections'][0]['category']['displayName'].rjust(3),  # alternative name
            'name': connection['sections'][0]['category']['shortName'].rjust(3),
            'direction': connection['sections'][0]['to']['name'],
            'barrierFree': 'disabled' in connection['sections'][0]['category']['journeyPreviewIconId'],
            'trafficJam': 'departureDelay' in connection['sections'][0]['from']
        }
        if line['trafficJam']:  # if there is a delay, use departureDelay value instead
            departure_time = time.strptime(connection['sections'][0]['from']['departureDelay'][:-3], "%Y-%m-%dT%H:%M:%S.")
        else:
            departure_time = time.strptime(connection['sections'][0]['from']['departure'][:-3], "%Y-%m-%dT%H:%M:%S.")
        countdown = round((time.mktime(departure_time) - time.mktime(time.localtime())) / 60)
        line['departures'] = [max(0, countdown)]
        station = {'lines': [line], 'name': connection['sections'][0]['from']['name']}
        return station 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: letsencrypt.py    MIT License 6 votes vote down vote up
def get_cert_days(module, cert_file):
    '''
    Return the days the certificate in cert_file remains valid and -1
    if the file was not found. If cert_file contains more than one
    certificate, only the first one will be considered.
    '''
    if not os.path.exists(cert_file):
        return -1

    openssl_bin = module.get_bin_path('openssl', True)
    openssl_cert_cmd = [openssl_bin, "x509", "-in", cert_file, "-noout", "-text"]
    dummy, out, dummy = module.run_command(openssl_cert_cmd, check_rc=True, encoding=None)
    try:
        not_after_str = re.search(r"\s+Not After\s*:\s+(.*)", out.decode('utf8')).group(1)
        not_after = datetime.fromtimestamp(time.mktime(time.strptime(not_after_str, '%b %d %H:%M:%S %Y %Z')))
    except AttributeError:
        module.fail_json(msg="No 'Not after' date found in {0}".format(cert_file))
    except ValueError:
        module.fail_json(msg="Failed to parse 'Not after' date of {0}".format(cert_file))
    now = datetime.utcnow()
    return (not_after - now).days


# function source: network/basics/uri.py 
Example 5
Project: flasky   Author: RoseOu   File: cookies.py    MIT License 6 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        expires = time.time() + morsel['max-age']
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = time.mktime(
            time.strptime(morsel['expires'], time_template)) - time.timezone
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 6
Project: AshsSDK   Author: thehappydinoa   File: cookies.py    MIT License 6 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        expires = time.time() + morsel['max-age']
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = time.mktime(
            time.strptime(morsel['expires'], time_template)) - time.timezone
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 7
Project: ngo-addons-backport   Author: camptocamp   File: cron.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def start_service():
    """ Start the above runner function in a daemon thread.

    The thread is a typical daemon thread: it will never quit and must be
    terminated when the main process exits - with no consequence (the processing
    threads it spawns are not marked daemon).

    """
    
    # Force call to strptime just before starting the cron thread
    # to prevent time.strptime AttributeError within the thread.
    # See: http://bugs.python.org/issue7980
    datetime.strptime('2012-01-01', '%Y-%m-%d')

    for i in range(openerp.tools.config['max_cron_threads']):
        def target():
            cron_runner(i)
        t = threading.Thread(target=target, name="openerp.service.cron.cron%d" % i)
        t.setDaemon(True)
        t.start()
        _logger.debug("cron%d started!" % i) 
Example 8
Project: ngo-addons-backport   Author: camptocamp   File: ir_property.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_by_record(self, cr, uid, record, context=None):
        if record.type in ('char', 'text'):
            return record.value_text
        elif record.type == 'float':
            return record.value_float
        elif record.type == 'boolean':
            return bool(record.value_integer)
        elif record.type == 'integer':
            return record.value_integer
        elif record.type == 'binary':
            return record.value_binary
        elif record.type == 'many2one':
            return record.value_reference
        elif record.type == 'datetime':
            return record.value_datetime
        elif record.type == 'date':
            if not record.value_datetime:
                return False
            return time.strftime('%Y-%m-%d', time.strptime(record.value_datetime, '%Y-%m-%d %H:%M:%S'))
        return False 
Example 9
Project: jawfish   Author: war-and-code   File: cookies.py    MIT License 6 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        expires = time.time() + morsel['max-age']
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = time.mktime(
            time.strptime(morsel['expires'], time_template)) - time.timezone
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 10
Project: blobfile   Author: cshesse   File: ops.py    The Unlicense 6 votes vote down vote up
def stat(path: str) -> Stat:
    """
    Stat a file or object representing a directory, returns a Stat object
    """
    if _is_local_path(path):
        s = os.stat(path)
        return Stat(size=s.st_size, mtime=s.st_mtime)
    elif _is_google_path(path):
        isfile, metadata = _google_isfile(path)
        if not isfile:
            raise FileNotFoundError(f"No such file: '{path}'")
        ts = time.strptime(
            metadata["updated"].replace("Z", "GMT"), "%Y-%m-%dT%H:%M:%S.%f%Z"
        )
        t = calendar.timegm(ts)
        return Stat(size=int(metadata["size"]), mtime=t)
    elif _is_azure_path(path):
        isfile, metadata = _azure_isfile(path)
        if not isfile:
            raise FileNotFoundError(f"No such file: '{path}'")
        ts = time.strptime(metadata["Last-Modified"], "%a, %d %b %Y %H:%M:%S %Z")
        t = calendar.timegm(ts)
        return Stat(size=int(metadata["Content-Length"]), mtime=t)
    else:
        raise Exception("unrecognized path") 
Example 11
Project: the-winged-hussars-plugin-for-edmc   Author: ryczypior   File: load.py    MIT License 6 votes vote down vote up
def process(self, logfile=None):
        basename = path.basename(logfile)
        print basename;
        if basename in ['Market.json', 'Shipyard.json', 'Outfitting.json', 'ModulesInfo.json']:
            try:
                with open(join(self.currentdir, basename), 'rb') as h:
                    data = h.read().strip()
                    if data:	# Can be empty if polling while the file is being re-written
                        entry = json.loads(data)

                        # Status file is shared between beta and live. So filter out status not in this game session.
                        if (timegm(time.strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) >= self.session_start and
                            self.status != entry):
                            self.status = entry
                            self.root.plugin_event_generate(basename, data);
            except:
                if __debug__: print_exc()
# singleton 
Example 12
Project: PT-help   Author: Rhilip   File: backtracking.py    MIT License 6 votes vote down vote up
def backtracking_id(site):
    cookies = cookies_raw2jar(site['cookies'])
    for _tid in range(site['start_torrent'], site['end_torrent'] + 2):
        t0 = time.time()

        _link = site['torrent_url'].format(_tid)
        torrent_page = requests.get(_link, cookies=cookies, headers=headers)
        title_search = re.search(site['search_ptn'], torrent_page.text)

        if title_search:
            _title = pymysql.escape_string(unescape(title_search.group("title")))
            pubDate = re.search("发布于(.+?)<", torrent_page.text).group(1)
            _timestamp = time.mktime(time.strptime(pubDate, "%Y-%m-%d %H:%M:%S"))

            wrap_insert(site=site['name'], sid=_tid, title=_title, link=_link, pubdate=_timestamp, t=t0)
        else:
            print("ID: {}, Cost: {:.5f} s, No torrent.".format(_tid, time.time() - t0))

        time.sleep(2) 
Example 13
Project: chattR   Author: patrickstocklin   File: cookies.py    GNU General Public License v2.0 6 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        expires = time.time() + morsel['max-age']
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = time.mktime(
            time.strptime(morsel['expires'], time_template)) - time.timezone
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 14
Project: Jtyoui   Author: jtyoui   File: parsetime.py    MIT License 6 votes vote down vote up
def change_time(self, day=0, hour=0, minute=0, week=0, second=0):
        """增加天数来修改时间"""
        add_time = datetime.timedelta(days=day, hours=hour, minutes=minute, weeks=week, seconds=second)
        if self.reduction:
            change = F'{self.now_year}-{self.now_mon}-{self.now_day} 00:00:00'  # 时分秒还原到0
            self.reduction = False
        else:
            change = self.str_time()
        add = datetime.datetime.strptime(change, self.format) + add_time
        self.now_year = add.year
        self.now_mon = add.month
        self.now_day = add.day
        self.now_hour = add.hour
        self.now_minute = add.minute
        self.now_second = add.second
        self.now_week = add.isoweekday() 
Example 15
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 16
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 17
Project: jumpserver-python-sdk   Author: jumpserver   File: utils.py    GNU General Public License v2.0 5 votes vote down vote up
def to_unixtime(time_string, format_string):
    with _STRPTIME_LOCK:
        return int(calendar.timegm(time.strptime(str(time_string), format_string))) 
Example 18
Project: pyblish-win   Author: pyblish   File: ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def cert_time_to_seconds(cert_time):
    """Return the time in seconds since the Epoch, given the timestring
    representing the "notBefore" or "notAfter" date from a certificate
    in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).

    "notBefore" or "notAfter" dates must use UTC (RFC 5280).

    Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
    UTC should be specified as GMT (see ASN1_TIME_print())
    """
    from time import strptime
    from calendar import timegm

    months = (
        "Jan","Feb","Mar","Apr","May","Jun",
        "Jul","Aug","Sep","Oct","Nov","Dec"
    )
    time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
    try:
        month_number = months.index(cert_time[:3].title()) + 1
    except ValueError:
        raise ValueError('time data %r does not match '
                         'format "%%b%s"' % (cert_time, time_format))
    else:
        # found valid month
        tt = strptime(cert_time[3:], time_format)
        # return an integer, the previous mktime()-based implementation
        # returned a float (fractional seconds are always zero here).
        return timegm((tt[0], month_number) + tt[2:6]) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_urllibnet.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_data_header(self):
        logo = "http://www.example.com/"
        file_location, fileheaders = self.urlretrieve(logo)
        os.unlink(file_location)
        datevalue = fileheaders.getheader('Date')
        dateformat = '%a, %d %b %Y %H:%M:%S GMT'
        try:
            time.strptime(datevalue, dateformat)
        except ValueError:
            self.fail('Date value not in %r format', dateformat) 
Example 20
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 21
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_feb29_on_leap_year_without_year(self):
        time.strptime("Feb 29", "%b %d") 
Example 22
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mar1_comes_after_feb29_even_when_omitting_the_year(self):
        self.assertLess(
                time.strptime("Feb 29", "%b %d"),
                time.strptime("Mar 1", "%b %d")) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_twelve_noon_midnight(self):
        eq = self.assertEqual
        eq(time.strptime('12 PM', '%I %p')[3], 12)
        eq(time.strptime('12 AM', '%I %p')[3], 0)
        eq(_strptime._strptime_time('12 PM', '%I %p')[3], 12)
        eq(_strptime._strptime_time('12 AM', '%I %p')[3], 0) 
Example 24
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 25
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 26
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 27
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def timetuple(self):
        return time.strptime(self.value, "%Y%m%dT%H:%M:%S") 
Example 28
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _datetime_type(data):
    t = time.strptime(data, "%Y%m%dT%H:%M:%S")
    return datetime.datetime(*tuple(t)[:6])

##
# Wrapper for binary data.  This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data. 
Example 29
Project: rail-line-animation-toolkit   Author: ZHZHH-Arezrh5100   File: query_schedule_12306.py    GNU General Public License v3.0 5 votes vote down vote up
def str2time(time_string):
    t = time.strptime(time_string, '%H:%M')
    return datetime.datetime(year=2000, month=1, day=1, hour=t.tm_hour, minute=t.tm_min)


# transfer time to string, use 3 ~ 26 hour one day 
Example 30
Project: wikiPlug   Author: gokturkgok   File: wikiPlug.py    GNU General Public License v3.0 5 votes vote down vote up
def get_track_length(duration):
    """
        Returns the track length in seconds for a wiki duration.
    """
    try:
        length = time.strptime(duration, '%M:%S')
    except ValueError:
        return None
    return length.tm_min * 60 + length.tm_sec

#---------------------------------------------------------------------- 
Example 31
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cookies.py    MIT License 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 32
Project: aurora   Author: carnby   File: auxiliary.py    MIT License 5 votes vote down vote up
def parse_twitter_date(str):
    naive_datetime = datetime.datetime(*(time.strptime(str, '%a %b %d %H:%M:%S +0000 %Y')[0:6]))
    return pytz.timezone("UTC").localize(naive_datetime)


# from http://farmdev.com/talks/unicode/ 
Example 33
Project: sic   Author: Yanixos   File: cookies.py    GNU General Public License v3.0 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 34
Project: bigquerylayers   Author: smandaric   File: dateandtime.py    GNU General Public License v3.0 5 votes vote down vote up
def strptime(text, dateFormat):
        return datetime(*(time.strptime(text, dateFormat)[0:6])) 
Example 35
Project: bigquerylayers   Author: smandaric   File: dateandtime.py    GNU General Public License v3.0 5 votes vote down vote up
def strptime(text, dateFormat):
        return datetime.strptime(text, dateFormat) 
Example 36
Project: bigquerylayers   Author: smandaric   File: cookies.py    GNU General Public License v3.0 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 37
Project: AshsSDK   Author: thehappydinoa   File: cookies.py    MIT License 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 38
Project: AshsSDK   Author: thehappydinoa   File: dateandtime.py    MIT License 5 votes vote down vote up
def strptime(text, dateFormat):
        return datetime(*(time.strptime(text, dateFormat)[0:6])) 
Example 39
Project: AshsSDK   Author: thehappydinoa   File: dateandtime.py    MIT License 5 votes vote down vote up
def strptime(text, dateFormat):
        return datetime.strptime(text, dateFormat) 
Example 40
Project: yz   Author: 6r6   File: cookies.py    MIT License 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 41
Project: douyin   Author: luocaiwei   File: tools.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def date_to_time(date):
    timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    _str = int(f'{timeStamp}000')
    return _str 
Example 42
Project: Kitsu.Bundle   Author: AeonLucid   File: cookies.py    MIT License 5 votes vote down vote up
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    ) 
Example 43
Project: ngo-addons-backport   Author: camptocamp   File: win32.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def nl_langinfo(param):
        if param == locale.D_FMT:
            val = time.strptime('30/12/2004', '%d/%m/%Y')
            dt = datetime.datetime(*val[:-2])
            format_date = dt.strftime('%x')
            for x, y in [('30', '%d'),('12', '%m'),('2004','%Y'),('04', '%Y')]:
                format_date = format_date.replace(x, y)
            return format_date
        if param == locale.T_FMT:
            val = time.strptime('13:24:56', '%H:%M:%S')
            dt = datetime.datetime(*val[:-2])
            format_time = dt.strftime('%X')
            for x, y in [('13', '%H'),('24', '%M'),('56','%S')]:
                format_time = format_time.replace(x, y)
            return format_time 
Example 44
Project: ngo-addons-backport   Author: camptocamp   File: ir_fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _str_to_date(self, cr, uid, model, column, value, context=None):
        try:
            time.strptime(value, DEFAULT_SERVER_DATE_FORMAT)
            return value, []
        except ValueError:
            raise ValueError(
                _(u"'%s' does not seem to be a valid date for field '%%(field)s'") % value, {
                    'moreinfo': _(u"Use the format '%s'") % u"2012-12-31"
                }) 
Example 45
Project: ngo-addons-backport   Author: camptocamp   File: ir_fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _str_to_datetime(self, cr, uid, model, column, value, context=None):
        if context is None: context = {}
        try:
            parsed_value = datetime.datetime.strptime(
                value, DEFAULT_SERVER_DATETIME_FORMAT)
        except ValueError:
            raise ValueError(
                _(u"'%s' does not seem to be a valid datetime for field '%%(field)s'") % value, {
                    'moreinfo': _(u"Use the format '%s'") % u"2012-12-31 23:59:59"
                })

        input_tz = self._input_tz(cr, uid, context)# Apply input tz to the parsed naive datetime
        dt = input_tz.localize(parsed_value, is_dst=False)
        # And convert to UTC before reformatting for writing
        return dt.astimezone(pytz.UTC).strftime(DEFAULT_SERVER_DATETIME_FORMAT), [] 
Example 46
Project: ngo-addons-backport   Author: camptocamp   File: hr_attendance.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _day_compute(self, cr, uid, ids, fieldnames, args, context=None):
        res = dict.fromkeys(ids, '')
        for obj in self.browse(cr, uid, ids, context=context):
            res[obj.id] = time.strftime('%Y-%m-%d', time.strptime(obj.name, '%Y-%m-%d %H:%M:%S'))
        return res 
Example 47
Project: ngo-addons-backport   Author: camptocamp   File: fleet.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def str_to_datetime(strdate):
    return datetime.datetime.strptime(strdate, tools.DEFAULT_SERVER_DATE_FORMAT) 
Example 48
Project: ngo-addons-backport   Author: camptocamp   File: fleet.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _year_get_fnc(self, cr, uid, ids, name, unknow_none, context=None):
        res = {}
        for record in self.browse(cr, uid, ids, context=context):
            if (record.date):
                res[record.id] = str(time.strptime(record.date, tools.DEFAULT_SERVER_DATE_FORMAT).tm_year)
            else:
                res[record.id] = _('Unknown')
        return res 
Example 49
Project: ngo-addons-backport   Author: camptocamp   File: fleet.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _search_contract_renewal_due_soon(self, cr, uid, obj, name, args, context):
        res = []
        for field, operator, value in args:
            assert operator in ('=', '!=', '<>') and value in (True, False), 'Operation not supported'
            if (operator == '=' and value == True) or (operator in ('<>', '!=') and value == False):
                search_operator = 'in'
            else:
                search_operator = 'not in'
            today = fields.date.context_today(self, cr, uid, context=context)
            datetime_today = datetime.datetime.strptime(today, tools.DEFAULT_SERVER_DATE_FORMAT)
            limit_date = str((datetime_today + relativedelta(days=+15)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT))
            cr.execute('select cost.vehicle_id, count(contract.id) as contract_number FROM fleet_vehicle_cost cost left join fleet_vehicle_log_contract contract on contract.cost_id = cost.id WHERE contract.expiration_date is not null AND contract.expiration_date > %s AND contract.expiration_date < %s AND contract.state IN (\'open\', \'toclose\') GROUP BY cost.vehicle_id', (today, limit_date))
            res_ids = [x[0] for x in cr.fetchall()]
            res.append(('id', search_operator, res_ids))
        return res 
Example 50
Project: ngo-addons-backport   Author: camptocamp   File: fleet.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def scheduler_manage_auto_costs(self, cr, uid, context=None):
        #This method is called by a cron task
        #It creates costs for contracts having the "recurring cost" field setted, depending on their frequency
        #For example, if a contract has a reccuring cost of 200 with a weekly frequency, this method creates a cost of 200 on the first day of each week, from the date of the last recurring costs in the database to today
        #If the contract has not yet any recurring costs in the database, the method generates the recurring costs from the start_date to today
        #The created costs are associated to a contract thanks to the many2one field contract_id
        #If the contract has no start_date, no cost will be created, even if the contract has recurring costs
        vehicle_cost_obj = self.pool.get('fleet.vehicle.cost')
        d = datetime.datetime.strptime(fields.date.context_today(self, cr, uid, context=context), tools.DEFAULT_SERVER_DATE_FORMAT).date()
        contract_ids = self.pool.get('fleet.vehicle.log.contract').search(cr, uid, [('state','!=','closed')], offset=0, limit=None, order=None,context=None, count=False)
        deltas = {'yearly': relativedelta(years=+1), 'monthly': relativedelta(months=+1), 'weekly': relativedelta(weeks=+1), 'daily': relativedelta(days=+1)}
        for contract in self.pool.get('fleet.vehicle.log.contract').browse(cr, uid, contract_ids, context=context):
            if not contract.start_date or contract.cost_frequency == 'no':
                continue
            found = False
            last_cost_date = contract.start_date
            if contract.generated_cost_ids:
                last_autogenerated_cost_id = vehicle_cost_obj.search(cr, uid, ['&', ('contract_id','=',contract.id), ('auto_generated','=',True)], offset=0, limit=1, order='date desc',context=context, count=False)
                if last_autogenerated_cost_id:
                    found = True
                    last_cost_date = vehicle_cost_obj.browse(cr, uid, last_autogenerated_cost_id[0], context=context).date
            startdate = datetime.datetime.strptime(last_cost_date, tools.DEFAULT_SERVER_DATE_FORMAT).date()
            if found:
                startdate += deltas.get(contract.cost_frequency)
            while (startdate <= d) & (startdate <= datetime.datetime.strptime(contract.expiration_date, tools.DEFAULT_SERVER_DATE_FORMAT).date()):
                data = {
                    'amount': contract.cost_generated,
                    'date': startdate.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
                    'vehicle_id': contract.vehicle_id.id,
                    'cost_subtype_id': contract.cost_subtype_id.id,
                    'contract_id': contract.id,
                    'auto_generated': True
                }
                cost_id = self.pool.get('fleet.vehicle.cost').create(cr, uid, data, context=context)
                startdate += deltas.get(contract.cost_frequency)
        return True