當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.replace方法代碼示例

本文整理匯總了Python中datetime.replace方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.replace方法的具體用法?Python datetime.replace怎麽用?Python datetime.replace使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime的用法示例。


在下文中一共展示了datetime.replace方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: strftime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def strftime(self, dt, fmt=None):
        """
        Refer to documentation for :meth:`datetime.datetime.strftime`

        *fmt* is a :meth:`datetime.datetime.strftime` format string.

        Warning: For years before 1900, depending upon the current
        locale it is possible that the year displayed with %x might
        be incorrect. For years before 100, %y and %Y will yield
        zero-padded strings.
        """
        if fmt is None:
            fmt = self.fmt
        fmt = self.illegal_s.sub(r"\1", fmt)
        fmt = fmt.replace("%s", "s")
        if dt.year >= 1900:
            # Note: in python 3.3 this is okay for years >= 1000,
            # refer to http://bugs.python.org/issue1777412
            return cbook.unicode_safe(dt.strftime(fmt))

        return self.strftime_pre_1900(dt, fmt) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:23,代碼來源:dates.py

示例2: __init__

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker._Edge_integer(base, 0)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         }
        if not hasattr(tz, 'localize'):
            # if tz is pytz, we need to do this w/ the localize fcn,
            # otherwise datetime.replace works fine...
            self.replaced['tzinfo'] = tz 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:19,代碼來源:dates.py

示例3: tick_values

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def tick_values(self, vmin, vmax):
        ymin = self.base.le(vmin.year) * self.base.step
        ymax = self.base.ge(vmax.year) * self.base.step

        vmin = vmin.replace(year=ymin, **self.replaced)
        if hasattr(self.tz, 'localize'):
            # look after pytz
            if not vmin.tzinfo:
                vmin = self.tz.localize(vmin, is_dst=True)

        ticks = [vmin]

        while True:
            dt = ticks[-1]
            if dt.year >= ymax:
                return date2num(ticks)
            year = dt.year + self.base.step
            dt = dt.replace(year=year, **self.replaced)
            if hasattr(self.tz, 'localize'):
                # look after pytz
                if not dt.tzinfo:
                    dt = self.tz.localize(dt, is_dst=True)

            ticks.append(dt) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:26,代碼來源:dates.py

示例4: autoscale

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def autoscale(self):
        """
        Set the view limits to include the data range.
        """
        dmin, dmax = self.datalim_to_dt()

        ymin = self.base.le(dmin.year)
        ymax = self.base.ge(dmax.year)
        vmin = dmin.replace(year=ymin, **self.replaced)
        vmin = vmin.astimezone(self.tz)
        vmax = dmax.replace(year=ymax, **self.replaced)
        vmax = vmax.astimezone(self.tz)

        vmin = date2num(vmin)
        vmax = date2num(vmax)
        return self.nonsingular(vmin, vmax) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:18,代碼來源:dates.py

示例5: datetime_to_timestamp

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def datetime_to_timestamp(datetime: datetime.datetime, time_units: str):
    """Converts a given datetime object and time units string
    into a netcdf timestamp integer with UTC encoding.

    Arguments:
        datetime {datetime.datetime} -- some datetime object
        time_units {str} -- time units (e.g. 'seconds since 1950-01-01 00:00:00')

    Returns:
        [int] -- timestamp integer
    """

    t = cftime.utime(time_units)

    datetime = datetime.replace(tzinfo=pytz.UTC)
    return t.date2num(datetime) 
開發者ID:DFO-Ocean-Navigator,項目名稱:Ocean-Data-Map-Project,代碼行數:18,代碼來源:utils.py

示例6: _from_ordinalf

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def _from_ordinalf(x, tz=None):
    """
    Convert Gregorian float of the date, preserving hours, minutes,
    seconds and microseconds.  Return value is a `.datetime`.

    The input date *x* is a float in ordinal days at UTC, and the output will
    be the specified `.datetime` object corresponding to that time in
    timezone *tz*, or if *tz* is ``None``, in the timezone specified in
    :rc:`timezone`.
    """
    if tz is None:
        tz = _get_rc_timezone()

    ix, remainder = divmod(x, 1)
    ix = int(ix)
    if ix < 1:
        raise ValueError('Cannot convert {} to a date.  This often happens if '
                         'non-datetime values are passed to an axis that '
                         'expects datetime objects.'.format(ix))
    dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)

    # Since the input date `x` float is unable to preserve microsecond
    # precision of time representation in non-antique years, the
    # resulting datetime is rounded to the nearest multiple of
    # `musec_prec`. A value of 20 is appropriate for current dates.
    musec_prec = 20
    remainder_musec = int(round(remainder * MUSECONDS_PER_DAY / musec_prec)
                          * musec_prec)

    # For people trying to plot with full microsecond precision, enable
    # an early-year workaround
    if x < 30 * 365:
        remainder_musec = int(round(remainder * MUSECONDS_PER_DAY))

    # add hours, minutes, seconds, microseconds
    dt += datetime.timedelta(microseconds=remainder_musec)

    return dt.astimezone(tz)


# a version of _from_ordinalf that can operate on numpy arrays 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:43,代碼來源:dates.py

示例7: _update_rrule

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def _update_rrule(self, **kwargs):
        tzinfo = self._base_tzinfo

        # rrule does not play nicely with time zones - especially pytz time
        # zones, it's best to use naive zones and attach timezones once the
        # datetimes are returned
        if 'dtstart' in kwargs:
            dtstart = kwargs['dtstart']
            if dtstart.tzinfo is not None:
                if tzinfo is None:
                    tzinfo = dtstart.tzinfo
                else:
                    dtstart = dtstart.astimezone(tzinfo)

                kwargs['dtstart'] = dtstart.replace(tzinfo=None)

        if 'until' in kwargs:
            until = kwargs['until']
            if until.tzinfo is not None:
                if tzinfo is not None:
                    until = until.astimezone(tzinfo)
                else:
                    raise ValueError('until cannot be aware if dtstart '
                                     'is naive and tzinfo is None')

                kwargs['until'] = until.replace(tzinfo=None)

        self._construct = kwargs.copy()
        self._tzinfo = tzinfo
        self._rrule = rrule(**self._construct) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:32,代碼來源:dates.py

示例8: _attach_tzinfo

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def _attach_tzinfo(self, dt, tzinfo):
        # pytz zones are attached by "localizing" the datetime
        if hasattr(tzinfo, 'localize'):
            return tzinfo.localize(dt, is_dst=True)

        return dt.replace(tzinfo=tzinfo) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:8,代碼來源:dates.py

示例9: to_local_timezone

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def to_local_timezone(self, datetime):
        """Returns a datetime object converted to the local timezone.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A ``datetime`` object normalized to a timezone.
        """
        if datetime.tzinfo is None:
            datetime = datetime.replace(tzinfo=pytz.UTC)

        return self.tzinfo.normalize(datetime.astimezone(self.tzinfo)) 
開發者ID:google,項目名稱:googleapps-message-recall,代碼行數:14,代碼來源:i18n.py

示例10: to_utc

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def to_utc(self, datetime):
        """Returns a datetime object converted to UTC and without tzinfo.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A naive ``datetime`` object (no timezone), converted to UTC.
        """
        if datetime.tzinfo is None:
            datetime = self.tzinfo.localize(datetime)

        return datetime.astimezone(pytz.UTC).replace(tzinfo=None) 
開發者ID:google,項目名稱:googleapps-message-recall,代碼行數:14,代碼來源:i18n.py

示例11: time_index_to_datetime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def time_index_to_datetime(timestamps, time_units: str):

    if isinstance(timestamps, np.ndarray):
        timestamps = timestamps.tolist()

    if not isinstance(timestamps, list):
        timestamps = [timestamps]

    result = [cftime.num2date(timestamp, time_units).replace(tzinfo=pytz.UTC) for timestamp in timestamps]

    if isinstance(result[0], list):
        return list(itertools.chain(*result))

    return result 
開發者ID:DFO-Ocean-Navigator,項目名稱:Ocean-Data-Map-Project,代碼行數:16,代碼來源:utils.py

示例12: _from_ordinalf

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def _from_ordinalf(x, tz=None):
    """
    Convert Gregorian float of the date, preserving hours, minutes,
    seconds and microseconds.  Return value is a `.datetime`.

    The input date *x* is a float in ordinal days at UTC, and the output will
    be the specified `.datetime` object corresponding to that time in
    timezone *tz*, or if *tz* is ``None``, in the timezone specified in
    :rc:`timezone`.
    """
    if tz is None:
        tz = _get_rc_timezone()

    ix, remainder = divmod(x, 1)
    ix = int(ix)
    if ix < 1:
        raise ValueError('Cannot convert {} to a date.  This often happens if '
                         'non-datetime values are passed to an axis that '
                         'expects datetime objects.'.format(ix))
    dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)

    # Since the input date `x` float is unable to preserve microsecond
    # precision of time representation in non-antique years, the
    # resulting datetime is rounded to the nearest multiple of
    # `musec_prec`. A value of 20 is appropriate for current dates.
    musec_prec = 20
    remainder_musec = int(round(remainder * MUSECONDS_PER_DAY / musec_prec)
                          * musec_prec)

    # For people trying to plot with full microsecond precision, enable
    # an early-year workaround
    if x < 30 * 365:
        remainder_musec = int(round(remainder * MUSECONDS_PER_DAY))

    # add hours, minutes, seconds, microseconds
    dt += datetime.timedelta(microseconds=remainder_musec)
    return dt.astimezone(tz)


# a version of _from_ordinalf that can operate on numpy arrays 
開發者ID:boris-kz,項目名稱:CogAlg,代碼行數:42,代碼來源:dates.py

示例13: strftime_pre_1900

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import replace [as 別名]
def strftime_pre_1900(self, dt, fmt=None):
        """Call time.strftime for years before 1900 by rolling
        forward a multiple of 28 years.

        *fmt* is a :func:`strftime` format string.

        Dalke: I hope I did this math right.  Every 28 years the
        calendar repeats, except through century leap years excepting
        the 400 year leap years.  But only if you're using the Gregorian
        calendar.
        """
        if fmt is None:
            fmt = self.fmt

        # Since python's time module's strftime implementation does not
        # support %f microsecond (but the datetime module does), use a
        # regular expression substitution to replace instances of %f.
        # Note that this can be useful since python's floating-point
        # precision representation for datetime causes precision to be
        # more accurate closer to year 0 (around the year 2000, precision
        # can be at 10s of microseconds).
        fmt = re.sub(r'((^|[^%])(%%)*)%f',
                     r'\g<1>{0:06d}'.format(dt.microsecond), fmt)

        year = dt.year
        # For every non-leap year century, advance by
        # 6 years to get into the 28-year repeat cycle
        delta = 2000 - year
        off = 6 * (delta // 100 + delta // 400)
        year = year + off

        # Move to between the years 1973 and 2000
        year1 = year + ((2000 - year) // 28) * 28
        year2 = year1 + 28
        timetuple = dt.timetuple()
        # Generate timestamp string for year and year+28
        s1 = time.strftime(fmt, (year1,) + timetuple[1:])
        s2 = time.strftime(fmt, (year2,) + timetuple[1:])

        # Replace instances of respective years (both 2-digit and 4-digit)
        # that are located at the same indexes of s1, s2 with dt's year.
        # Note that C++'s strftime implementation does not use padded
        # zeros or padded whitespace for %y or %Y for years before 100, but
        # uses padded zeros for %x. (For example, try the runnable examples
        # with .tm_year in the interval [-1900, -1800] on
        # http://en.cppreference.com/w/c/chrono/strftime.) For ease of
        # implementation, we always use padded zeros for %y, %Y, and %x.
        s1, s2 = self._replace_common_substr(s1, s2,
                                             "{0:04d}".format(year1),
                                             "{0:04d}".format(year2),
                                             "{0:04d}".format(dt.year))
        s1, s2 = self._replace_common_substr(s1, s2,
                                             "{0:02d}".format(year1 % 100),
                                             "{0:02d}".format(year2 % 100),
                                             "{0:02d}".format(dt.year % 100))
        return cbook.unicode_safe(s1) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:58,代碼來源:dates.py


注:本文中的datetime.replace方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。