Python datetime.datetime.replace() Examples

The following are 21 code examples of datetime.datetime.replace(). 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 also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: dates.py    From pySINDy with MIT License 6 votes vote down vote up
def untokenize_pattern(tokens):
    """
    Turn a date format pattern token stream back into a string.

    This is the reverse operation of ``tokenize_pattern``.

    :type tokens: Iterable[tuple]
    :rtype: str
    """
    output = []
    for tok_type, tok_value in tokens:
        if tok_type == "field":
            output.append(tok_value[0] * tok_value[1])
        elif tok_type == "chars":
            if not any(ch in PATTERN_CHARS for ch in tok_value):  # No need to quote
                output.append(tok_value)
            else:
                output.append("'%s'" % tok_value.replace("'", "''"))
    return "".join(output) 
Example #2
Source File: dates.py    From pySINDy with MIT License 6 votes vote down vote up
def _format_fallback_interval(start, end, skeleton, tzinfo, locale):
    if skeleton in locale.datetime_skeletons:  # Use the given skeleton
        format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale)
    elif all((isinstance(d, date) and not isinstance(d, datetime)) for d in (start, end)):  # Both are just dates
        format = lambda dt: format_date(dt, locale=locale)
    elif all((isinstance(d, time) and not isinstance(d, date)) for d in (start, end)):  # Both are times
        format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale)
    else:
        format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale)

    formatted_start = format(start)
    formatted_end = format(end)

    if formatted_start == formatted_end:
        return format(start)

    return (
        locale.interval_formats.get(None, "{0}-{1}").
        replace("{0}", formatted_start).
        replace("{1}", formatted_end)
    ) 
Example #3
Source File: dates.py    From pySINDy with MIT License 5 votes vote down vote up
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    datetime = _ensure_datetime_tzinfo(_get_datetime(datetime), tzinfo)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale) 
Example #4
Source File: common.py    From itchatmp with MIT License 5 votes vote down vote up
def filter_request(self, request):
        if self._serverList is None:
            t = threading.Thread(target=self.set_server_list)
            t.setDaemon = True
            t.start()
            def clear_server_list():
                self._serverList = None
            self.core.ioLoop.call_later(
                (datetime.replace(datetime.now() + timedelta(days=1), 
                hour=0, minute=5, second=0) - datetime.now()).seconds,
                clear_server_list)
        if not self._serverList:
            logger.debug('Server list is loading, so ignore verifying once.')
            return True
        return request.remote_ip in self._serverList 
Example #5
Source File: common.py    From itchatmp with MIT License 5 votes vote down vote up
def set_server_list(self):
        self._serverList = []
        serverList, fetchTime = self.core.atStorage.get_server_list()
        if fetchTime < time.mktime(datetime.replace(datetime.now(),
            hour=0, minute=0, second=0).timetuple()):
            r = self._serverIpFn()
            if not r:
                logger.debug(r)
            else:
                self._serverList = r.get('ip_list', [])
                self.core.atStorage.store_server_list(self._serverList, time.time())
        else:
            self._serverList = serverList 
Example #6
Source File: common.py    From itchatmp with MIT License 5 votes vote down vote up
def maintain_thread(self, firstCallResult=None):
        ''' thread to update token and
        register next update event into event loop '''
        r = firstCallResult or self._syncTokenFunction()
        if not r:
            self.core.ioLoop.call_later(
                (datetime.replace(datetime.now() + timedelta(days=1), 
                hour=0, minute=5, second=0) - datetime.now()).seconds,
                self.maintain_access_token, None)
        else:
            self.core.ioLoop.call_later(r['expires_in'] - 30,
                self.maintain_access_token, None) 
Example #7
Source File: core.py    From dwdweather2 with MIT License 5 votes vote down vote up
def datetime_to_int(self, datetime):
        return int(datetime.replace("T", "").replace(":", "")) 
Example #8
Source File: interpreter.py    From course-activity-planner with GNU General Public License v3.0 5 votes vote down vote up
def _get_new_datetime(self, datetime, relative_mod, time_mod):
        """Build new datetime from relative and time modifiers."""
        if relative_mod:
            datetime += relative_mod

        if time_mod:
            return datetime.replace(hour=time_mod.hour, minute=time_mod.minute)

        return datetime 
Example #9
Source File: dates.py    From pySINDy with MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example #10
Source File: dates.py    From pySINDy with MIT License 5 votes vote down vote up
def _get_time(time, tzinfo=None):
    """
    Get a timezoned time from a given instant.

    .. warning:: The return values of this function may depend on the system clock.

    :param time: time, datetime or None
    :rtype: time
    """
    if time is None:
        time = datetime.utcnow()
    elif isinstance(time, number_types):
        time = datetime.utcfromtimestamp(time)
    if time.tzinfo is None:
        time = time.replace(tzinfo=UTC)
    if isinstance(time, datetime):
        if tzinfo is not None:
            time = time.astimezone(tzinfo)
            if hasattr(tzinfo, 'normalize'):  # pytz
                time = tzinfo.normalize(time)
        time = time.timetz()
    elif tzinfo is not None:
        time = time.replace(tzinfo=tzinfo)
    return time 
Example #11
Source File: dates.py    From pySINDy with MIT License 5 votes vote down vote up
def _ensure_datetime_tzinfo(datetime, tzinfo=None):
    """
    Ensure the datetime passed has an attached tzinfo.

    If the datetime is tz-naive to begin with, UTC is attached.

    If a tzinfo is passed in, the datetime is normalized to that timezone.

    >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1)).tzinfo.zone
    'UTC'

    >>> tz = get_timezone("Europe/Stockholm")
    >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour
    14

    :param datetime: Datetime to augment.
    :param tzinfo: Optional tznfo.
    :return: datetime with tzinfo
    :rtype: datetime
    """
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'):  # pytz
            datetime = tzinfo.normalize(datetime)
    return datetime 
Example #12
Source File: client.py    From ton_client with Mozilla Public License 2.0 5 votes vote down vote up
def wallet_send_grams(self, public_key, secret, dest_address, seq_no: int, valid_until: datetime, amount, message=''):
        """
        TL Spec
            wallet.sendGrams private_key:inputKey destination:accountAddress seqno:int32 valid_until:int53 amount:int64 message:bytes
                = SendGramsResult;
            inputKey key:key local_password:secureBytes = InputKey;
            key public_key:string secret:secureBytes = Key;
            accountAddress account_address:string = AccountAddress;
            sendGramsResult sent_until:int53 = SendGramsResult;
        :param public_key:
        :param secret:
        :param dest_address:
        :param seq_no:
        :param valid_until:
        :param amount:
        :param message:
        :return:
        """
        if valid_until.tzname() is None:
            valid_until = datetime.replace(tzinfo=timezone.utc)
        valid_until_ts = valid_until.timestamp()

        data = {
            '@type': 'wallet.sendGrams',
            'private_key': {
                'key': {
                    'public_key': public_key,
                    'secret': secret
                }
            },
            'destination': {
                'account_address': dest_address
            },
            'seqno': seq_no,
            'valid_until': valid_until_ts,
            'amount': amount,
            'message': message
        }

        r = self._t_local.tonlib.ton_async_execute(data)
        return r 
Example #13
Source File: dates.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example #14
Source File: dates.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale) 
Example #15
Source File: dates.py    From pySINDy with MIT License 4 votes vote down vote up
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    dt = _get_datetime(dt).replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    ) 
Example #16
Source File: dates.py    From sndlatr with Apache License 2.0 4 votes vote down vote up
def get_next_timezone_transition(zone=None, dt=None):
    """Given a timezone it will return a :class:`TimezoneTransition` object
    that holds the information about the next timezone transition that's going
    to happen.  For instance this can be used to detect when the next DST
    change is going to happen and how it looks like.

    The transition is calculated relative to the given datetime object.  The
    next transition that follows the date is used.  If a transition cannot
    be found the return value will be `None`.

    Transition information can only be provided for timezones returned by
    the :func:`get_timezone` function.

    :param zone: the timezone for which the transition should be looked up.
                 If not provided the local timezone is used.
    :param dt: the date after which the next transition should be found.
               If not given the current time is assumed.
    """
    zone = get_timezone(zone)
    if dt is None:
        dt = datetime.utcnow()
    else:
        dt = dt.replace(tzinfo=None)

    if not hasattr(zone, '_utc_transition_times'):
        raise TypeError('Given timezone does not have UTC transition '
                        'times.  This can happen because the operating '
                        'system fallback local timezone is used or a '
                        'custom timezone object')

    try:
        idx = max(0, bisect_right(zone._utc_transition_times, dt))
        old_trans = zone._transition_info[idx - 1]
        new_trans = zone._transition_info[idx]
        old_tz = zone._tzinfos[old_trans]
        new_tz = zone._tzinfos[new_trans]
    except (LookupError, ValueError):
        return None

    return TimezoneTransition(
        activates=zone._utc_transition_times[idx],
        from_tzinfo=old_tz,
        to_tzinfo=new_tz,
        reference_date=dt
    ) 
Example #17
Source File: dates.py    From pySINDy with MIT License 4 votes vote down vote up
def parse_pattern(pattern):
    """Parse date, time, and datetime format patterns.

    >>> parse_pattern("MMMMd").format
    u'%(MMMM)s%(d)s'
    >>> parse_pattern("MMM d, yyyy").format
    u'%(MMM)s %(d)s, %(yyyy)s'

    Pattern can contain literal strings in single quotes:

    >>> parse_pattern("H:mm' Uhr 'z").format
    u'%(H)s:%(mm)s Uhr %(z)s'

    An actual single quote can be used by using two adjacent single quote
    characters:

    >>> parse_pattern("hh' o''clock'").format
    u"%(hh)s o'clock"

    :param pattern: the formatting pattern to parse
    """
    if type(pattern) is DateTimePattern:
        return pattern

    if pattern in _pattern_cache:
        return _pattern_cache[pattern]

    result = []

    for tok_type, tok_value in tokenize_pattern(pattern):
        if tok_type == "chars":
            result.append(tok_value.replace('%', '%%'))
        elif tok_type == "field":
            fieldchar, fieldnum = tok_value
            limit = PATTERN_CHARS[fieldchar]
            if limit and fieldnum not in limit:
                raise ValueError('Invalid length for field: %r'
                                 % (fieldchar * fieldnum))
            result.append('%%(%s)s' % (fieldchar * fieldnum))
        else:
            raise NotImplementedError("Unknown token type: %s" % tok_type)

    _pattern_cache[pattern] = pat = DateTimePattern(pattern, u''.join(result))
    return pat 
Example #18
Source File: client.py    From ton_client with Mozilla Public License 2.0 4 votes vote down vote up
def raw_get_transactions(self, account_address: str, from_transaction_lt: str, from_transaction_hash: str):
        """
        TL Spec:
            raw.getTransactions account_address:accountAddress from_transaction_id:internal.transactionId = raw.Transactions;
            accountAddress account_address:string = AccountAddress;
            internal.transactionId lt:int64 hash:bytes = internal.TransactionId;
        :param account_address: str with raw or user friendly address
        :param from_transaction_lt: from transaction lt
        :param from_transaction_hash: from transaction hash in HEX representation
        :return: dict as
            {
                '@type': 'raw.transactions',
                'transactions': list[dict as {
                    '@type': 'raw.transaction',
                    'utime': int,
                    'data': str,
                    'transaction_id': internal.transactionId,
                    'fee': str,
                    'in_msg': dict as {
                        '@type': 'raw.message',
                        'source': str,
                        'destination': str,
                        'value': str,
                        'message': str
                    },
                    'out_msgs': list[dict as raw.message]
                }],
                'previous_transaction_id': internal.transactionId
            }
        """
        if len(account_address.split(':')) == 2:
            account_address = raw_to_userfriendly(account_address)

        from_transaction_hash = codecs.encode(codecs.decode(from_transaction_hash, 'hex'), 'base64').decode().replace("\n", "")

        data = {
            '@type': 'raw.getTransactions',
            'account_address': {
              'account_address': account_address,
            },
            'from_transaction_id': {
                '@type': 'internal.transactionId',
                'lt': from_transaction_lt,
                'hash': from_transaction_hash
            }
        }
        r = self._t_local.tonlib.ton_async_execute(data)
        return r 
Example #19
Source File: core.py    From dwdweather2 with MIT License 4 votes vote down vote up
def import_measures(self, station_id, current=False, latest=False, historic=False):
        """
        Load data from DWD server.
        Parameter:

        station_id: e.g. 2667 (Köln-Bonn airport)

        latest: Load most recent data (True, False)
        historic: Load older values

        We download ZIP files for several categories
        of measures. We then extract one file from
        each ZIP. This path is then handed to the
        CSV -> Sqlite import function.
        """

        # Compute timerange labels / subfolder names.
        timeranges = []
        if current:
            timeranges.append("now")
        if latest:
            timeranges.append("recent")
        if historic:
            timeranges.append("historical")

        # Reporting.
        station_info = self.station_info(station_id)
        log.info("Downloading measurements for station %d and timeranges %s" % (station_id, timeranges))
        log.info(
            "Station information: %s"
            % json.dumps(station_info, indent=2, sort_keys=True)
        )

        # Download and import data.
        for category in self.categories:
            key = category["key"]
            name = category["name"].replace("_", " ")
            log.info('Downloading "{}" data ({})'.format(name, key))
            for result in self.cdc.get_measurements(station_id, category, timeranges):
                # Import data for all categories.
                log.info(
                    'Importing measurements for station "{}" and category "{}"'.format(
                        station_id, category
                    )
                )
                # log.warning("No files to import for station %s" % station_id)
                self.import_measures_textfile(result) 
Example #20
Source File: dates.py    From sndlatr with Apache License 2.0 4 votes vote down vote up
def format_datetime(datetime=None, format='medium', tzinfo=None,
                    locale=LC_TIME):
    r"""Return a date formatted according to the given pattern.

    >>> dt = datetime(2007, 04, 01, 15, 30)
    >>> format_datetime(dt, locale='en_US')
    u'Apr 1, 2007, 3:30:00 PM'

    For any pattern requiring the display of the time-zone, the third-party
    ``pytz`` package is needed to explicitly specify the time-zone:

    >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
    ...                 locale='fr_FR')
    u'dimanche 1 avril 2007 17:30:00 heure avanc\xe9e d\u2019Europe centrale'
    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
    ...                 tzinfo=get_timezone('US/Eastern'), locale='en')
    u'2007.04.01 AD at 11:30:00 EDT'

    :param datetime: the `datetime` object; if `None`, the current date and
                     time is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param tzinfo: the timezone to apply to the time for display
    :param locale: a `Locale` object or a locale identifier
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, number_types):
        datetime = datetime_.utcfromtimestamp(datetime)
    elif isinstance(datetime, time):
        datetime = datetime_.combine(date.today(), datetime)
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    if tzinfo is not None:
        datetime = datetime.astimezone(get_timezone(tzinfo))
        if hasattr(tzinfo, 'normalize'): # pytz
            datetime = tzinfo.normalize(datetime)

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        return get_datetime_format(format, locale=locale) \
            .replace("'", "") \
            .replace('{0}', format_time(datetime, format, tzinfo=None,
                                        locale=locale)) \
            .replace('{1}', format_date(datetime, format, locale=locale))
    else:
        return parse_pattern(format).apply(datetime, locale) 
Example #21
Source File: dates.py    From sndlatr with Apache License 2.0 4 votes vote down vote up
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
    """Return the timezone associated with the given `datetime` object formatted
    as string indicating the offset from GMT.

    >>> dt = datetime(2007, 4, 1, 15, 30)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT+00:00'

    >>> tz = get_timezone('America/Los_Angeles')
    >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
    >>> get_timezone_gmt(dt, locale='en')
    u'GMT-08:00'
    >>> get_timezone_gmt(dt, 'short', locale='en')
    u'-0800'

    The long format depends on the locale, for example in France the acronym
    UTC string is used instead of GMT:

    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
    u'UTC-08:00'

    .. versionadded:: 0.9

    :param datetime: the ``datetime`` object; if `None`, the current date and
                     time in UTC is used
    :param width: either "long" or "short"
    :param locale: the `Locale` object, or a locale string
    """
    if datetime is None:
        datetime = datetime_.utcnow()
    elif isinstance(datetime, integer_types):
        datetime = datetime_.utcfromtimestamp(datetime).time()
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    locale = Locale.parse(locale)

    offset = datetime.tzinfo.utcoffset(datetime)
    seconds = offset.days * 24 * 60 * 60 + offset.seconds
    hours, seconds = divmod(seconds, 3600)
    if width == 'short':
        pattern = u'%+03d%02d'
    else:
        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
    return pattern % (hours, seconds // 60)