Python datetime.strptime() Examples

The following are code examples for showing how to use datetime.strptime(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: test_timeseries.py    (license) View Source Project 7 votes vote down vote up
def test_NaT_methods(self):
        # GH 9513
        raise_methods = ['astimezone', 'combine', 'ctime', 'dst',
                         'fromordinal', 'fromtimestamp', 'isocalendar',
                         'strftime', 'strptime', 'time', 'timestamp',
                         'timetuple', 'timetz', 'toordinal', 'tzname',
                         'utcfromtimestamp', 'utcnow', 'utcoffset',
                         'utctimetuple']
        nat_methods = ['date', 'now', 'replace', 'to_datetime', 'today']
        nan_methods = ['weekday', 'isoweekday']

        for method in raise_methods:
            if hasattr(NaT, method):
                self.assertRaises(ValueError, getattr(NaT, method))

        for method in nan_methods:
            if hasattr(NaT, method):
                self.assertTrue(np.isnan(getattr(NaT, method)()))

        for method in nat_methods:
            if hasattr(NaT, method):
                self.assertIs(getattr(NaT, method)(), NaT)

        # GH 12300
        self.assertEqual(NaT.isoformat(), 'NaT') 
Example 2
Project: rc-niceties   Author: mjec   File: config.py    (license) View Source Project 6 votes vote down vote up
def from_frontend_value(key, value):
    """Returns a `SiteConfiguration` object value for the relevant `key` and
    JSON-serializable `value`, applying any transformation reversed by to_frontend_value."""
    if key == NICETIES_OPEN:
        from datetime import timedelta
        return timedelta(days=value)
    elif key == CLOSING_TIME:
        from datetime import datetime
        return datetime.strptime(value, '%H:%M').time()
    elif key == CLOSING_BUFFER:
        from datetime import timedelta
        return timedelta(minutes=value)
    elif key == CACHE_TIMEOUT:
        from datetime import timedelta
        return timedelta(seconds=value)
    elif key == INCLUDE_FACULTY:
        return value
    elif key == INCLUDE_RESIDENTS:
        return value
    else:
        raise ValueError('No such config key!') 
Example 3
Project: InplusTrader_Linux   Author: zhengwsh   File: mongo.py    (license) View Source Project 6 votes vote down vote up
def test(self):
		cx = self.Symbol_Db['equity'].find()
		symbolSet = set([d['code'] for d in cx])
		for code in symbolSet:
			start = self.Symbol_Db['equity'].find({"code" : code})[0]['timeToMarket']
			try:
				start = datetime.datetime.strptime(str(start), '%Y%m%d')
			except :
				print code
			
			start = start.strftime("%Y-%m-%d")
			print start
		return 


	#---------------------------------------------------------------------- 
Example 4
Project: cpp-boilerplate   Author: xwvvvvwx   File: gtest_xml_output_unittest.py    (license) View Source Project 6 votes vote down vote up
def testTimestampValue(self):
    """Checks whether the timestamp attribute in the XML output is valid.

    Runs a test program that generates an empty XML output, and checks if
    the timestamp attribute in the testsuites tag is valid.
    """
    actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0)
    date_time_str = actual.documentElement.getAttributeNode('timestamp').value
    # datetime.strptime() is only available in Python 2.5+ so we have to
    # parse the expected datetime manually.
    match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
    self.assertTrue(
        re.match,
        'XML datettime string %s has incorrect format' % date_time_str)
    date_time_from_xml = datetime.datetime(
        year=int(match.group(1)), month=int(match.group(2)),
        day=int(match.group(3)), hour=int(match.group(4)),
        minute=int(match.group(5)), second=int(match.group(6)))

    time_delta = abs(datetime.datetime.now() - date_time_from_xml)
    # timestamp value should be near the current local time
    self.assertTrue(time_delta < datetime.timedelta(seconds=600),
                    'time_delta is %s' % time_delta)
    actual.unlink() 
Example 5
Project: antares   Author: CONABIO   File: test_util.py    (license) View Source Project 6 votes vote down vote up
def test_rapideye_sensor(self):
        '''
        Test an instance of the rapideye sensor class to check if it parses its
        attributes correctly.
        '''
        import madmex.mapper.sensor.rapideye as rapideye
        import datetime
        path = '/LUSTRE/MADMEX/eodata/rapideye/1447720/2013/2013-02-11/l3a/1447720_2013-02-11_RE3_3A_182802_metadata.xml'
        sensor = rapideye.Sensor(path)
        self.assertEqual(sensor.get_attribute(rapideye.ANGLE), 3.96)
        self.assertEqual(sensor.get_attribute(rapideye.PRODUCT_NAME), 'L3A')
        self.assertEqual(sensor.get_attribute(rapideye.SENSOR), 'OPTICAL')
        self.assertEqual(sensor.get_attribute(rapideye.PLATFORM), 'RE-3')
        self.assertEqual(sensor.get_attribute(rapideye.CREATION_DATE), '2013-04-26T17:48:34Z')
        self.assertEqual(sensor.get_attribute(rapideye.ACQUISITION_DATE), datetime.datetime.strptime('2013-02-11T18:04:21.337522Z', "%Y-%m-%dT%H:%M:%S.%fZ"))
        self.assertEqual(sensor.get_attribute(rapideye.CLOUDS), 0.0)
        self.assertEqual(sensor.get_attribute(rapideye.AZIMUTH_ANGLE), 278.21)
        self.assertEqual(sensor.get_attribute(rapideye.SOLAR_AZIMUTH), 162.0359)
        self.assertEqual(sensor.get_attribute(rapideye.SOLAR_ZENITH), 56.02738)
        self.assertEqual(sensor.get_attribute(rapideye.TILE_ID), 1447720) 
Example 6
Project: Flask_Blog   Author: sugarguo   File: processors.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 7
Project: smc-python   Author: gabstopper   File: util.py    (license) View Source Project 5 votes vote down vote up
def datetime_to_ms(dt):
    """
    Convert an unaware datetime object to milliseconds. This will
    be a UTC time. The SMC stores all times in UTC and will do the
    time conversions based on the local timezone.
    Example of converting a datetime to milliseconds::
    
        utc_time = datetime.strptime("2018-06-04T00:00:00", "%Y-%m-%dT%H:%M:%S")
        datetime_to_ms(utc_time)
    
    :param dt datetime: pass in python datetime object.
    :return: value representing the datetime in milliseconds
    :rtype: int
    """
    return int(time.mktime(dt.timetuple()) * 1000) 
Example 8
Project: magdalena   Author: KaiRo-at   File: datautils.py    (license) View Source Project 5 votes vote down vote up
def verifyForcedDates(fdates):
    from datetime import datetime
    import re
    force_dates = [];
    for fdate in fdates:
        if (re.match(r"\d+-\d+-\d+", fdate) and
            datetime.strptime(fdate, '%Y-%m-%d').strftime('%Y-%m-%d') == fdate):
            force_dates.append(fdate);
    return force_dates 
Example 9
Project: magdalena   Author: KaiRo-at   File: datautils.py    (license) View Source Project 5 votes vote down vote up
def dayStringAdd(anaday, days = 0, weeks = 0):
    from datetime import datetime, timedelta
    return (datetime.strptime(anaday, '%Y-%m-%d') + timedelta(days=days, weeks=weeks)).strftime('%Y-%m-%d') 
Example 10
Project: magdalena   Author: KaiRo-at   File: datautils.py    (license) View Source Project 5 votes vote down vote up
def dayStringBeforeDelta(anaday, tdelta):
    from datetime import datetime
    return (datetime.strptime(anaday, '%Y-%m-%d') - tdelta).strftime('%Y-%m-%d') 
Example 11
Project: lagbot   Author: mikevb1   File: management.py    (license) View Source Project 5 votes vote down vote up
def date(argument):
    formats = ('%Y/%m/%d', '%Y-%m-%d')
    for fmt in formats:
        try:
            return datetime.strptime(argument, fmt)
        except ValueError:
            continue
    raise commands.BadArgument('Cannot convert to date. Expected YYYY/MM/DD or YYYY-MM-DD.') 
Example 12
Project: QXSConsolas   Author: qxsch   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 13
Project: InplusTrader_Linux   Author: zhengwsh   File: mongo.py    (license) View Source Project 5 votes vote down vote up
def get_range_min_tick_data(self, code, start=None, end=None, ktype=1):
		start = str(fc.get_stock_timeToMarket(code)) if start is None else start
		end = str(datetime.datetime.today().date()) if end is None else end

		startD = datetime.datetime.strptime(start, '%Y-%m-%d')
		endD = datetime.datetime.strptime(end, '%Y-%m-%d')

		delta = datetime.timedelta(days=1)
		inDate = endD - delta

		while inDate >= startD:
			self.parse(code, inDate.strftime("%Y-%m-%d"), ktype)
			inDate -= delta 
Example 14
Project: InplusTrader_Linux   Author: zhengwsh   File: mongo.py    (license) View Source Project 5 votes vote down vote up
def downloadEquityAllData(self, code):
		start = self.Symbol_Db['equity'].find({"code" : code})[0]['timeToMarket']
		try:
			start = datetime.datetime.strptime(str(start), '%Y%m%d')
		except:
			return
		start = start.strftime("%Y-%m-%d")

		self.get_range_daily_data(code, start) #default????
		self.get_range_min_tick_data(code, start)
		# ??index?????????
		self.Tick_Db[code].ensure_index([('date', pymongo.DESCENDING)])
		self.OneMin_Db[code].ensure_index([('date', pymongo.DESCENDING)]) 
Example 15
Project: InplusTrader_Linux   Author: zhengwsh   File: mongo.py    (license) View Source Project 5 votes vote down vote up
def updateEquityAllData(self, code):
		# find the latest timestamp in collection.
		latest = self.Daily_Db[code].find_one(sort=[('date', pymongo.DESCENDING)])['date']
		latest = datetime.datetime.strptime(str(latest), '%Y-%m-%d')
		start = datetime.datetime.strftime(latest + timedelta(days=1), '%Y-%m-%d')
		
		self.get_range_daily_data(code, start) #default????
		self.get_range_min_tick_data(code, start) 
Example 16
Project: InplusTrader_Linux   Author: zhengwsh   File: mongo.py    (license) View Source Project 5 votes vote down vote up
def loadMcCsv(self, fileName, dbName, symbol):
		"""?Multicharts???csv??????????Mongo????"""
		import csv

		start = time()
		print u'????CSV??%s???????%s?%s?' %(fileName, dbName, symbol)

		# ??????????
		host, port = loadMongoSetting()

		client = pymongo.MongoClient(host, port)    
		collection = client[dbName][symbol]
		collection.ensure_index([('datetime', pymongo.ASCENDING)], unique=True)   

		# ???????????
		reader = csv.DictReader(file(fileName, 'r'))
		for d in reader:
			bar = CtaBarData()
			bar.vtSymbol = symbol
			bar.symbol = symbol
			bar.open = float(d['Open'])
			bar.high = float(d['High'])
			bar.low = float(d['Low'])
			bar.close = float(d['Close'])
			bar.date = datetime.strptime(d['Date'], '%Y/%m/%d').strftime('%Y%m%d')
			bar.time = d['Time']
			bar.datetime = datetime.strptime(bar.date + ' ' + bar.time, '%Y%m%d %H:%M:%S')
			bar.volume = d['TotalVolume']

			flt = {'datetime': bar.datetime}
			collection.update_one(flt, {'$set':bar.__dict__}, upsert=True)  
			print bar.date, bar.time

		print u'????????%s' % (time()-start) 
Example 17
Project: SSURGO-QA   Author: ncss-tech   File: SSURGO_BatchDownload.py    (license) View Source Project 5 votes vote down vote up
def GetTabularDate(newFolder):
    # Get string for SAVEREST date from tabular/sacatlog.txt file
    # Use it to compare with the date from the WSS dataset
    # If the existing database is same or newer, it will be kept and the WSS version skipped
    # The original string looks like this: 12/05/2013 23:44:00
    #
    # Return YYYYMMDD as integer

    try:
        tabDate = 0

        # Try finding the text file in the tabular folder and reading SAVEREST from that file.
        saCatalog = os.path.join(newFolder, r"tabular\sacatlog.txt")

        if arcpy.Exists(saCatalog):
            fh = open(saCatalog, "r")
            rec = fh.readline()
            fh.close()
            # Example date (which is index 3 in pipe-delimited file):  9/23/2014 6:49:27
            vals = rec.split("|")
            recDate = vals[3]
            wssDate = "%m/%d/%Y %H:%M:%S"  # string date format used for SAVEREST in text file
            intDate = "%Y%m%d"             # YYYYMMDD format for comparison
            dateObj = datetime.strptime(recDate, wssDate)
            tabDate = int(dateObj.strftime(intDate))

        else:
            AddMsgAndPrint(" \nUnable to find file: " + saCatalog, 1)

        return tabDate

    except:
        errorMsg()
        return tabDate

## =================================================================================== 
Example 18
Project: flasky   Author: RoseOu   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 19
Project: dramameter   Author: cygenb0ck   File: analyze.py    (license) View Source Project 5 votes vote down vote up
def plot_by_all( data ):
    x_vals = list()
    y_vals = list()
    for k in sorted(data):
        x_vals.append( datetime.datetime.strptime(k, key_pattern) )
        y_vals.append(data[k])

    x_vals2 = matplotlib.dates.date2num(x_vals)

    plt.clf()
    #plt.plot_date(x_vals2, y_vals)
    plt.plot(x_vals2, y_vals)
    plt.show() 
Example 20
Project: dramameter   Author: cygenb0ck   File: analyze.py    (license) View Source Project 5 votes vote down vote up
def plot_by_interval(data, zamg_dfs = None):
    p_vals = {}
    # sort by year
    for k in sorted(data):
        v = data[k]
        d_obj = datetime.datetime.strptime(k, key_pattern)

        series_key = datetime.datetime.strftime(d_obj, "%Y")
        #data_key = datetime.datetime.strftime(d_obj, "%m-%d")

        p_vals.setdefault(series_key, dict()).setdefault("x_vals", list()).append(d_obj)
        p_vals.setdefault(series_key, dict()).setdefault("y_vals", list()).append(v)

    plt.clf()

    fig, axis = plt.subplots(nrows=len(p_vals)*2, sharex=False, sharey=False)

    a_iter = iter(axis)

    for k in sorted(p_vals):
        v = p_vals[k]
        ax = next(a_iter)

        y_vals = v["y_vals"]
        x_vals = matplotlib.dates.date2num(v["x_vals"])
        ax.plot_date(x_vals, y_vals)
        # ax.plot(x_vals, y_vals)

        ax = next(a_iter)
        if zamg_dfs is not None and k in zamg_dfs:
            df = zamg_dfs[k]
            df['Wien Hohe Warte']['48,2486']['16,3564']['198.0']['Anhöhe']['Ebene']\
                ['Lufttemperatur']['Lufttemperatur um 14 MEZ (°C)'].plot(ax=ax)

    plt.show() 
Example 21
Project: dramameter   Author: cygenb0ck   File: analyze.py    (license) View Source Project 5 votes vote down vote up
def reformat_dateteime( in_date, in_pattern, out_pattern ):
    d = datetime.datetime.strptime(in_date, in_pattern)
    return datetime.datetime.strftime(d, out_pattern) 
Example 22
Project: check_katello_sync   Author: stdevel   File: check_katello_sync.py    (license) View Source Project 5 votes vote down vote up
def check_product(product):
    """
    Checks a product for currency.

    :param product: Product dictionary
    :type product: dict
    """
    global PROD_OK, PROD_WARN, PROD_CRIT

    #check if product unsynced
    if product["last_sync"] == None:
        LOGGER.debug("Product '{0}' ({1}) is UNSYNCED!".format(
            product["label"], product["description"]
        ))
        PROD_CRIT.append(product["label"])
        set_code(2)
    else:
        LOGGER.debug("Product '{0}' ({1}) was synced at {2}".format(
            product["label"], product["description"], product["last_sync"][0:19]
        ))
        last_sync = datetime.strptime(
            product["last_sync"][0:19], "%Y-%m-%d %H:%M:%S"
        )
        delta = datetime.now() - last_sync
        LOGGER.debug("Delta for '{0}' is {1} days".format(
            product["label"], delta.days
        ))
        if delta.days > options.outdated_crit:
            PROD_CRIT.append(product["label"])
            set_code(2)
            LOGGER.debug("Critical product: '{0}'".format(product["label"]))
        if delta.days > options.outdated_warn:
            PROD_WARN.append(product["label"])
            set_code(1)
            LOGGER.debug("Warning product: '{0}'".format(product["label"]))
        else:
            PROD_OK.append(product["label"])
            LOGGER.debug("Ok product: '{0}'".format(product["label"])) 
Example 23
Project: splunk_app   Author: passivetotal   File: utilities.py    (license) View Source Project 5 votes vote down vote up
def valid_date(input_date):
    """Validate input dates against a certain format.

    :param str input_date: Date value to check
    :return: Loaded date value
    """
    try:
        return datetime.strptime(input_date, "%Y-%m-%d")
    except ValueError:
        msg = "Not a valid date: '{0}'.".format(input_date)
        raise argparse.ArgumentTypeError(msg) 
Example 24
Project: oa_qian   Author: sunqb   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 25
Project: TestRewrite   Author: osqa-interns   File: test_start_late_homework_student.py    (license) View Source Project 5 votes vote down vote up
def get_new_set_time(seconds_added = 60):
    """
    -Helper function used in order to create
    an assignment that will be due very soon (late assignmnet)

    -Should be a very easy process for most cases, but deals with all the
    difficulties for you
    -The new time computed is calculated from the local time

    Uses datetime.datetime

    :param seconds_added: number of seconds from
    now that you want the due date of the assignment to be
    :return:
    string of format HHMMpm/am which you can enter directly into the due time
    textbox in order to set the due time
    """
    # get current time and time at which to make it due
    time_now = datetime.now()
    time_now = time_now + timedelta(seconds=seconds_added)
    time_string = str(time_now.hour) + str(time_now.minute)

    time_structure = datetime.strptime(time_string,"%H%M")
    # time_structure is a datetime.datetime object

    time_string_reform = time_structure.strftime("%I%M%p")
    # ^ set_time comes in format "HH MM am/pm"

    return time_string_reform


################ 
Example 26
Project: plexdevices   Author: coryo   File: media.py    (license) View Source Project 5 votes vote down vote up
def _originally_available_at(self):
        return datetime.strptime(self.data.get('originallyAvailableAt',
                                               '0000-00-00'),
                                 '%Y-%m-%d').date() 
Example 27
Project: chihu   Author: yelongyu   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 28
Project: ShelbySearch   Author: Agentscreech   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 29
Project: pyetje   Author: rorlika   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                "- value is not a string." %
                                (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(zip(groups.iterkeys(),
                                        map(int, groups.itervalues()))))
            else:
                return type_(*map(int, m.groups(0)))
    return process 
Example 30
Project: Price-Comparator   Author: Thejas-1   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 31
Project: Flask-NvRay-Blog   Author: rui7157   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 32
Project: Flask-NvRay-Blog   Author: rui7157   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 33
Project: Callandtext   Author: iaora   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 34
Project: python_ddd_flask   Author: igorvinnicius   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 35
Project: Python-Plex-Controller   Author: MoeFwacky   File: system.py    (license) View Source Project 5 votes vote down vote up
def timechecker(thing):
	thing = thing.lower()
	thing = thing.replace("now + ","now+")
	if ("now+" in thing):
		import datetime
		thing = thing.replace("now+","")
		if ("m" in thing):
		
                        thing = thing.replace("m","")
                        thing = int(thing)
                        now = datetime.datetime.now()
                        thing = str(now + datetime.timedelta(minutes = thing))
		elif ("h" in thing):
			thing = thing.replace("h","")
			thing = int(thing)
			now = datetime.datetime.now()
			thing = str(now + datetime.timedelta(hours = thing))

		thing = thing.split(" ")
		thing = thing[1]
		thing = thing.split(":")
		hr = thing[0]
		min = thing[1]
		thing = hr + ":" + min
		
	if (" am" in thing):
		thing = thing.replace(" am"," AM")
	if (" pm" in thing):
		thing = thing.replace(" pm"," PM")
	cck = thing
	cck = thing.split(":")
	cck = thing[0]
	if ((cck > 0) and ("am" not in thing.lower()) and ("pm" not in thing.lower())):
		#print ("Given 24hr time. Converting...")
		from datetime import datetime
		d = datetime.strptime(thing, "%H:%M")
		thedate = d.strftime("%-I:%M %p")
	else:
		thedate = thing
	return thedate 
Example 36
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: test_timeseries.py    (license) View Source Project 5 votes vote down vote up
def test_to_datetime_format_microsecond(self):
        val = '01-Apr-2011 00:00:01.978'
        format = '%d-%b-%Y %H:%M:%S.%f'
        result = to_datetime(val, format=format)
        exp = datetime.strptime(val, format)
        self.assertEqual(result, exp) 
Example 37
Project: django-vimeo   Author: suquant   File: storage.py    (license) View Source Project 5 votes vote down vote up
def accessed_time(self, name):
        res = self.client.get(name)
        res.raise_for_status()
        res = res.json()
        utc_datetime = res.get('modified_time')
        return datetime.strptime(utc_datetime, '%Y-%m-%dT%H:%M:%SZ') 
Example 38
Project: django-vimeo   Author: suquant   File: storage.py    (license) View Source Project 5 votes vote down vote up
def created_time(self, name):
        res = self.client.get(name)
        res.raise_for_status()
        res = res.json()
        utc_datetime = res.get('created_time')
        return datetime.strptime(utc_datetime, '%Y-%m-%dT%H:%M:%SZ') 
Example 39
Project: rucio   Author: rucio01   File: srmdumps.py    (license) View Source Project 5 votes vote down vote up
def get_newest(base_url, url_pattern, links):
    '''
    Returns a tuple with the newest url in the `links` list matching the
    pattern `url_pattern` and a datetime object representing the creation
    date of the url.

    The creation date is extracted from the url using datetime.strptime().
    '''
    logger = logging.getLogger('auditor.srmdumps')
    times = []

    pattern_components = url_pattern.split('/')

    date_pattern = '{0}/{1}'.format(base_url, pattern_components[0])
    if len(pattern_components) > 1:
        postfix = '/' + '/'.join(pattern_components[1:])
    else:
        postfix = ''

    for link in links:
        try:
            time = datetime.datetime.strptime(link, date_pattern)
        except ValueError:
            pass
        else:
            times.append((str(link) + postfix, time))

    if not times:
        msg = 'No links found matching the pattern {0} in {1}'.format(date_pattern, links)
        logger.error(msg)
        raise Exception(msg)

    return max(times, key=operator.itemgetter(1)) 
Example 40
Project: webapp   Author: superchilli   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 41
Project: Chromium_DepotTools   Author: p07r0457   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_gerrit(date_string):
  return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f000') 
Example 42
Project: Chromium_DepotTools   Author: p07r0457   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_rietveld(date_string):
  try:
    return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
  except ValueError:
    # Sometimes rietveld returns a value without the milliseconds part, so we
    # attempt to parse those cases as well.
    return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') 
Example 43
Project: Chromium_DepotTools   Author: p07r0457   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_google_code(date_string):
  return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ') 
Example 44
Project: QualquerMerdaAPI   Author: tiagovizoto   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 45
Project: gardenbot   Author: GoestaO   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 46
Project: flask-zhenai-mongo-echarts   Author: Fretice   File: processors.py    (license) View Source Project 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example 47
Project: node-gn   Author: Shouqun   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_gerrit(date_string):
  return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f000') 
Example 48
Project: node-gn   Author: Shouqun   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_rietveld(date_string):
  try:
    return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
  except ValueError:
    # Sometimes rietveld returns a value without the milliseconds part, so we
    # attempt to parse those cases as well.
    return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') 
Example 49
Project: node-gn   Author: Shouqun   File: my_activity.py    (license) View Source Project 5 votes vote down vote up
def datetime_from_google_code(date_string):
  return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ') 
Example 50
Project: Commons2Data   Author: Commonists   File: items.py    (license) View Source Project 5 votes vote down vote up
def unexpired(date):
    if isinstance(date,str):
        return datetime.now() - datetime.strptime(date, dateFormat) > delta
    else:
        return  datetime.now() - date > delta