本文整理匯總了Python中datetime.date.replace方法的典型用法代碼示例。如果您正苦於以下問題:Python date.replace方法的具體用法?Python date.replace怎麽用?Python date.replace使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime.date
的用法示例。
在下文中一共展示了date.replace方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_time
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
示例2: _format_fallback_interval
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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)
)
示例3: untokenize_pattern
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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)
示例4: test_sys_favourites_and_dates
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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"
)
示例5: __init__
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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)
示例6: get_day_of_year
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
示例7: strip_tags
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
def strip_tags(value):
"Return the given HTML with all tags stripped."
# TODO(danvk): replace this with something correct.
return re.sub(r'<[^>]*?>', '', value)
示例8: AbbreviateMonths
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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')
示例9: CleanTitle
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
def CleanTitle(title):
"""remove [graphic] from titles"""
title = title.replace(' [graphic].', '')
title = title.replace('[', '').replace(']','')
return title
示例10: CleanDate
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
示例11: CleanFolder
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
示例12: _ensure_datetime_tzinfo
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
示例13: format_datetime
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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)
示例14: get_payer_plan_period_date
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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
# -----------------------------------
示例15: date2int
# 需要導入模塊: from datetime import date [as 別名]
# 或者: from datetime.date import replace [as 別名]
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