Python datetime.date.replace() Examples
The following are 23
code examples of datetime.date.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.date
, or try the search function
.
Example #1
Source File: dates.py From pySINDy with MIT License | 6 votes |
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 |
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: record.py From oldnyc with Apache License 2.0 | 5 votes |
def CleanFolder(folder): # remove leading 'Folder: ', trailing period & convert various forms of # dashes to a single form of slashes. if not folder: return '' if folder[-1] == '.' and not folder[-3] == '.': # e.g. 'Y.M.C.A' folder = folder[:-1] folder = folder.replace('Folder: ', '') folder = re.sub(r' *- *', ' / ', folder) return folder
Example #4
Source File: conv.py From WikiTalkParser with MIT License | 5 votes |
def unescape(s): s = unescapeHTML(s) s = unescapeHTML(s) if '%' in s: s = urllib.unquote(s) s = s.replace('_', ' ') return s
Example #5
Source File: conv.py From WikiTalkParser with MIT License | 5 votes |
def date2int(date): date = unescapeHTML(date) p = re.compile(r'(?:,|[.]|[|]|[[]|[]]|th|nd|rd|(&\S+?;)|nbsp;)') date = p.sub(' ', date) date = date.replace('1st', '1') blankP = re.compile(r'\s+') date = blankP.sub(' ', date) try: i = int(time.mktime(time.strptime(date, '%H:%M %d %B %Y (%Z)'))) except ValueError: try: i = int(time.mktime(time.strptime(date, '%H:%M %d %b %Y (%Z)'))) except ValueError: try: i = int(time.mktime(time.strptime(date, '%H:%M %B %d %Y (%Z)'))) except ValueError: try: i = int(time.mktime(time.strptime(date, '%H:%M %b %d %Y (%Z)'))) except ValueError: #try: # i = int(time.mktime(time.strptime(date, '%H:%M %d %B %Y'))) #except ValueError: # try: # i = int(time.mktime(time.strptime(date, '%H:%M %d %b %Y'))) # except ValueError: # try: # i = int(time.mktime(time.strptime(date, '%H:%M %B %d %Y'))) # except ValueError: # try: # i = int(time.mktime(time.strptime(date, '%H:%M %b %d %Y'))) # except ValueError: i = -1 return i if debugDate: raw_input("[date2int]: " + date + " to " + str(i)) #date is in seconds; translate it into minutes return i/60
Example #6
Source File: CMS_SynPuf_ETL_CDM_v5.py From ETL-CMS with Apache License 2.0 | 5 votes |
def get_payer_plan_period_date(date, delta): m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 # calculate new month and year if m == 0: m = 12 d = min(date.day, calendar.monthrange(y, m)[1]) # get the last date of the month return date.replace(day=d,month=m, year=y) # return the new date # ----------------------------------- # Write Location records # -----------------------------------
Example #7
Source File: dates.py From pySINDy with MIT License | 5 votes |
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 #8
Source File: dates.py From pySINDy with MIT License | 5 votes |
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 #9
Source File: dates.py From pySINDy with MIT License | 5 votes |
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 #10
Source File: dates.py From pySINDy with MIT License | 5 votes |
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 #11
Source File: test_system.py From gphotos-sync with MIT License | 5 votes |
def test_sys_favourites_and_dates(self): """Download favourite images in test library. Also Check that dates are set correctly """ s = ts.SetupDbAndCredentials() args = ["--favourites-only", "--max-retries", "6", "--max-threads", "2"] s.test_setup("test_sys_favourites", args=args, trash_files=True, trash_db=True) s.gp.start(s.parsed_args) db = LocalData(s.root) # Total of 1 out of media items db.cur.execute("SELECT COUNT() FROM SyncFiles") count = db.cur.fetchone() self.assertEqual(1, count[0]) name = s.root / "photos/2017/09/IMG_2117.JPG" date = datetime.fromtimestamp(os.path.getmtime(str(name))) expected = datetime(2017, 9, 26, 15, 29, 44) self.assertEqual( expected, date.replace(microsecond=0), "Modify date not set correctly" ) if os.name == "nt": date = datetime.fromtimestamp(os.path.getctime(name)) expected = datetime(2017, 9, 26, 15, 29, 44) self.assertEqual( expected, date.replace(microsecond=0), "Create date not set correctly" )
Example #12
Source File: record.py From oldnyc with Apache License 2.0 | 5 votes |
def CleanDate(date): """remove [] and trailing period from dates""" if not date: return '' date = date.replace('[', '').replace(']','').replace('\n', ' ') if date[-1] == '.': date = date[:-1] return date
Example #13
Source File: record.py From oldnyc with Apache License 2.0 | 5 votes |
def CleanTitle(title): """remove [graphic] from titles""" title = title.replace(' [graphic].', '') title = title.replace('[', '').replace(']','') return title
Example #14
Source File: record.py From oldnyc with Apache License 2.0 | 5 votes |
def AbbreviateMonths(txt): return txt.replace('January', 'Jan') \ .replace('February', 'Feb') \ .replace('March', 'Mar') \ .replace('April', 'Apr') \ .replace('June', 'Jun') \ .replace('July', 'Jul') \ .replace('August', 'Aug') \ .replace('September', 'Sep') \ .replace('October', 'Oct') \ .replace('Novemeber', 'Nov') \ .replace('December', 'Dec') \ .replace('Sept', 'Sep')
Example #15
Source File: record.py From oldnyc with Apache License 2.0 | 5 votes |
def strip_tags(value): "Return the given HTML with all tags stripped." # TODO(danvk): replace this with something correct. return re.sub(r'<[^>]*?>', '', value)
Example #16
Source File: dates.py From sndlatr with Apache License 2.0 | 5 votes |
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 #17
Source File: dates.py From sndlatr with Apache License 2.0 | 5 votes |
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 #18
Source File: dates.py From pySINDy with MIT License | 4 votes |
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 #19
Source File: models.py From silverstrike with MIT License | 4 votes |
def update_date(self, date=None, save=False): """ Calculates the date to the next occurence and optionally saves it. It uses the usual_month_day if set for setting the correct day in a monthly recurrence """ delta = None if not date: date = self.date if self.interval == self.MONTHLY: delta = relativedelta(months=1) elif self.interval == self.QUARTERLY: delta = relativedelta(months=3) elif self.interval == self.BIANNUALLY: delta = relativedelta(months=6) elif self.interval == self.ANNUALLY: delta = relativedelta(years=1) elif self.interval == self.WEEKLY: delta = relativedelta(weeks=1) elif self.interval == self.DAILY: delta = relativedelta(days=1) else: return delta *= self.multiplier while True: date += delta if self.usual_month_day > 0 and self.interval not in [self.WEEKLY, self.DAILY]: day = self.usual_month_day while True: try: date = date.replace(day=day) break except ValueError: day -= 1 pass if date.weekday() > 4 and self.interval not in [self.WEEKLY, self.DAILY]: if self.weekend_handling == self.SKIP: continue elif self.weekend_handling == self.NEXT_WEEKDAY: date += relativedelta(days=7 - date.weekday()) elif self.weekend_handling == self.PREVIOUS_WEEKDAY: date -= relativedelta(days=date.weekday() - 4) if save: self.date = date self.save() return date
Example #20
Source File: dates.py From pySINDy with MIT License | 4 votes |
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 #21
Source File: dates.py From sndlatr with Apache License 2.0 | 4 votes |
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 #22
Source File: dates.py From sndlatr with Apache License 2.0 | 4 votes |
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)
Example #23
Source File: dates.py From sndlatr with Apache License 2.0 | 4 votes |
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 )