Python time.replace() Examples

The following are 12 code examples for showing how to use time.replace(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: vnpy_crypto   Author: birforce   File: bitmexGateway.py    License: MIT License 6 votes vote down vote up
def onTick(self, d):
        """"""
        symbol = d['symbol']

        tick = self.tickDict.get(symbol, None)
        if not tick:
            return

        tick.lastPrice = d['price']

        date, time = str(d['timestamp']).split('T')
        tick.date = date.replace('-', '')
        tick.time = time.replace('Z', '')
        tick.datetime = datetime.now()

        self.gateway.onTick(tick)

    # ---------------------------------------------------------------------- 
Example 2
Project: vnpy_crypto   Author: birforce   File: bitmexGateway.py    License: MIT License 6 votes vote down vote up
def onDepth(self, d):
        """"""
        symbol = d['symbol']
        tick = self.tickDict.get(symbol, None)
        if not tick:
            return

        for n, buf in enumerate(d['bids'][:5]):
            price, volume = buf
            tick.__setattr__('bidPrice%s' % (n + 1), price)
            tick.__setattr__('bidVolume%s' % (n + 1), volume)

        for n, buf in enumerate(d['asks'][:5]):
            price, volume = buf
            tick.__setattr__('askPrice%s' % (n + 1), price)
            tick.__setattr__('askVolume%s' % (n + 1), volume)

        date, time = str(d['timestamp']).split('T')
        tick.date = date.replace('-', '')
        tick.time = time.replace('Z', '')

        self.gateway.onTick(tick)

    # ---------------------------------------------------------------------- 
Example 3
Project: MultiExplorer   Author: priestc   File: views.py    License: MIT License 6 votes vote down vote up
def historical_price(request):
    fiat = request.GET['fiat'].upper()
    crypto = request.GET['currency'].upper()
    try:
        time = arrow.get(request.GET['time']).datetime
    except:
        return http.JsonResponse({'error': "Invalid Time argument"}, status=400)

    try:
        price = PriceTick.nearest(crypto, fiat, time)
    except PriceTick.DoesNotExist:
        return http.JsonResponse(
            {'error': "Can't get historical price for %s->%s" % (fiat, crypto)},
            status=400
        )

    try:
        naive_time = time.replace(tzinfo=None)
        price['estimated_supply'] = SupplyEstimator(crypto).calculate_supply(at_time=naive_time)
    except NotImplementedError:
        pass

    price['currency'] = crypto
    return http.JsonResponse(price) 
Example 4
Project: suds   Author: suds-community   File: date.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __parse(value):
        """
        Parse the string date.

        Supports the subset of ISO8601 used by xsd:time, but is lenient with
        what is accepted, handling most reasonable syntax.

        Subsecond information is rounded to microseconds due to a restriction
        in the python datetime.time implementation.

        @param value: A time string.
        @type value: str
        @return: A time object.
        @rtype: B{datetime}.I{time}

        """
        match_result = _RE_TIME.match(value)
        if match_result is None:
           raise ValueError("date data has invalid format '%s'" % (value,))

        time, round_up = _time_from_match(match_result)
        tzinfo = _tzinfo_from_match(match_result)
        if round_up:
            time = _bump_up_time_by_microsecond(time)
        return time.replace(tzinfo=tzinfo) 
Example 5
Project: vnpy_crypto   Author: birforce   File: bitmexGateway.py    License: MIT License 5 votes vote down vote up
def onTrade(self, d):
        """"""
        if not d['lastQty']:
            return

        tradeID = d['execID']
        if tradeID in self.tradeSet:
            return
        self.tradeSet.add(tradeID)

        trade = VtTradeData()
        trade.gatewayName = self.gatewayName

        trade.symbol = d['symbol']
        trade.exchange = EXCHANGE_BITMEX
        trade.vtSymbol = '.'.join([trade.symbol, trade.exchange])
        if d['clOrdID']:
            orderID = d['clOrdID']
        else:
            orderID = d['orderID']
        trade.orderID = orderID
        trade.vtOrderID = '.'.join([trade.gatewayName, trade.orderID])

        trade.tradeID = tradeID
        trade.vtTradeID = '.'.join([trade.gatewayName, trade.tradeID])

        trade.direction = directionMapReverse[d['side']]
        trade.price = d['lastPx']
        trade.volume = d['lastQty']
        trade.tradeTime = d['timestamp'][0:22].replace('T', '')

        self.gateway.onTrade(trade)

    # ---------------------------------------------------------------------- 
Example 6
Project: vnpy_crypto   Author: birforce   File: bitmexGateway.py    License: MIT License 5 votes vote down vote up
def onOrder(self, d):
        """"""
        if 'ordStatus' not in d:
            return

        sysID = d['orderID']
        if sysID in self.orderDict:
            order = self.orderDict[sysID]
        else:
            order = VtOrderData()
            order.gatewayName = self.gatewayName

            order.symbol = d['symbol']
            order.exchange = EXCHANGE_BITMEX
            order.vtSymbol = '.'.join([order.symbol, order.exchange])

            if d['clOrdID']:
                orderID = d['clOrdID']
            else:
                orderID = sysID
            order.orderID = orderID
            order.vtOrderID = '.'.join([self.gatewayName, order.orderID])

            order.direction = directionMapReverse[d['side']]

            if d['price']:
                order.price = d['price']

            order.totalVolume = d['orderQty']
            order.orderTime = d['timestamp'][0:10].replace('-', '')

            self.orderDict[sysID] = order

        order.tradedVolume = d.get('cumQty', order.tradedVolume)
        order.status = statusMapReverse.get(d['ordStatus'], STATUS_UNKNOWN)

        self.gateway.onOrder(order)

        # ---------------------------------------------------------------------- 
Example 7
Project: pyatv   Author: postlund   File: utils.py    License: MIT License 5 votes vote down vote up
def faketime(module_name, *times):
    """Monkey patch datetime.now to return fake time."""

    class FakeDatetime:
        def __init__(self, times):
            self.times = times

        def __enter__(self):
            module = import_module(module_name)
            setattr(module.datetime, "datetime", self)

        def __exit__(self, exc_type, exc_val, exc_tb):
            module = import_module(module_name)
            setattr(module.datetime, "datetime", datetime)

        def now(self, tz=None):
            """Replace times from now to fake values."""
            if not self.time:
                return datetime.now(tz=tz)

            next_time = self.times[0]
            if len(self.times) > 1:
                self.times = self.times[1:]

            time = datetime.fromtimestamp(next_time)
            if tz:
                time = time.replace(tzinfo=tz)
            return time

        def __call__(self, *args, **kwargs):
            return datetime(*args, **kwargs)

        def __getattr__(self, attr):
            """Redirect non-stubbed functions to original module."""
            return getattr(datetime, attr)

    return FakeDatetime(list(times)) 
Example 8
Project: Medium_Scraper   Author: harrisonjansma   File: medium_scraper.py    License: Apache License 2.0 5 votes vote down vote up
def get_titles_from_cards(cards):
    #PULLS TITLE DATA FROM EACH CARD IN CARDS, RETURNS A LIST OF TITLES
    def title_cleaner(title):
        #REMOVE MEDIUMS ENCODING SYMBOLS AND EMOJIS FROM TITLES
        title = title.replace("\xa0"," ")
        title = title.replace("\u200a","")
        title = title.replace("\ufe0f","")
        title = re.sub(r'[^\x00-\x7F]+','', title)
        return title

    titles=[]
    for card in cards:
        #SEARCH FOR TITLE THERE ARE 3 DIFF CLASSES
        variant1 = card.find("h3", class_="graf graf--h3 graf-after--figure graf--title")
        variant2 = card.find("h3", class_="graf graf--h3 graf-after--figure graf--trailing graf--title")
        variant3 = card.find("h4", class_="graf graf--h4 graf--leading")
        variant4 = card.find("h3", class_="graf graf--h3 graf--leading graf--title")
        variant5 = card.find("p", class_="graf graf--p graf--leading")
        variant6 = card.find("h3", class_="graf graf--h3 graf--startsWithDoubleQuote graf--leading graf--title")
        variant7= card.find("h3", class_="graf graf--h3 graf--startsWithDoubleQuote graf-after--figure graf--trailing graf--title")
        #EACH CARD MUST HAVE ONE OF THE ABOVE TITLE CLASSES FIND IT AND CUT OUT MEDIUM'S
        #STYLING CODES
        variants = [variant1, variant2, variant3, variant4, variant5, variant6, variant7]
        saved = False
        #THE FIRST TITLE ENTRY WE MATCH, WE SAVE
        for variant in variants:
            if ((variant is not None) and (not saved)):
                title = variant.text
                title = title_cleaner(title)
                titles.append(title)
                saved = True
        if not saved:
            titles.append("NaN")
    return titles 
Example 9
Project: Medium_Scraper   Author: harrisonjansma   File: medium_scraper.py    License: Apache License 2.0 5 votes vote down vote up
def get_subtitles_from_cards(cards):
    #PULLS TITLE DATA FROM EACH CARD IN CARDS, RETURNS A LIST OF TITLES
    def subtitle_cleaner(subtitle):
        #REMOVE MEDIUMS ENCODING SYMBOLS AND EMOJIS FROM TITLES
        subtitle = subtitle.replace("\xa0"," ")
        subtitle = subtitle.replace("\u200a","")
        subtitle = subtitle.replace("\ufe0f","")
        subtitle = re.sub(r'[^\x00-\x7F]+','', subtitle)
        return subtitle

    subtitles=[]
    for card in cards:
        #SEARCH FOR TITLE THERE ARE 3 DIFF CLASSES
        variant1 = card.find("h4", class_="graf graf--h4 graf-after--h3 graf--subtitle")
        variant2 = card.find("h4", class_="graf graf--h4 graf-after--h3 graf--trailing graf--subtitle")
        variant3 = card.find("strong", class_="markup--strong markup--p-strong")
        variant4 = card.find("h4", class_="graf graf--p graf-after--h3 graf--trailing")
        variant5= card.find("p", class_="graf graf--p graf-after--h3 graf--trailing")
        variant6= card.find("blockquote", class_="graf graf--pullquote graf-after--figure graf--trailing")
        variant7 = card.find("p", class_="graf graf--p graf-after--figure")
        variant8 = card.find("blockquote", class_="graf graf--blockquote graf-after--h3 graf--trailing")
        variant9 = card.find("p", class_="graf graf--p graf-after--figure graf--trailing")
        variant10 = card.find("em", class_="markup--em markup--p-em")
        variant11=card.find("p", class_="graf graf--p graf-after--p graf--trailing")
        #EACH CARD MUST HAVE ONE OF THE TITLE CLASSES FIND IT AND CUT OUT MEDIUM'S
        #STYLING CODES
        variants = [variant1, variant2, variant3, variant4, variant5, variant6, variant7, variant8, variant9, variant10, variant11]
        saved = False
        for variant in variants:
            if ((variant is not None) and (not saved)):
                subtitle = variant.text
                subtitle = subtitle_cleaner(subtitle)
                subtitles.append(subtitle)
                saved = True
        if not saved:
            subtitles.append("NaN")
    return subtitles 
Example 10
Project: Medium_Scraper   Author: harrisonjansma   File: medium_scraper.py    License: Apache License 2.0 5 votes vote down vote up
def get_readTime_from_cards(cards):
    #PULL READTIME FROM EACH CARD IN CARDS
    readingTimes=[]
    for card in cards:
        time = card.find("span", class_="readingTime")
        if time is not None:
            time = time['title']
            time = time.replace(" min read", "")
            readingTimes.append(time)
        else:
            readingTimes.append("0")
    return readingTimes 
Example 11
Project: suds   Author: suds-community   File: date.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __parse(value):
        """
        Parse the string datetime.

        Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
        with what is accepted, handling most reasonable syntax.

        Subsecond information is rounded to microseconds due to a restriction
        in the python datetime.datetime/time implementation.

        @param value: A datetime string.
        @type value: str
        @return: A datetime object.
        @rtype: B{datetime}.I{datetime}

        """
        match_result = _RE_DATETIME.match(value)
        if match_result is None:
           raise ValueError("date data has invalid format '%s'" % (value,))

        date = _date_from_match(match_result)
        time, round_up = _time_from_match(match_result)
        tzinfo = _tzinfo_from_match(match_result)

        value = datetime.datetime.combine(date, time)
        value = value.replace(tzinfo=tzinfo)
        if round_up:
            value += datetime.timedelta(microseconds=1)
        return value 
Example 12
Project: suds   Author: suds-community   File: date.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __is_daylight_time(self, dt):
        if not time.daylight:
            return False
        time_tuple = dt.replace(tzinfo=None).timetuple()
        time_tuple = time.localtime(time.mktime(time_tuple))
        return time_tuple.tm_isdst > 0