日期格式化为月份大写
Date formatting to month uppercase
我设法在
之前得到了约会对象
import datetime
getDate = datetime.date.today()
print(getDate.strftime("%Y-%B-%d"))
输出为 2018-June-23
但我想像这样格式化输出:2018-JUNE-23
(月份是大写的)
只需使用.upper()
:
print(getDate.strftime("%Y-%B-%d").upper())
要直接在格式字符串中执行此操作,请在月份 (^
) 前加上 carrot:
>>> getDate = datetime.date.today()
>>> print(getDate.strftime("%Y-%^B-%d"))
2018-JUNE-22
注意:如果您的平台上有可用的 glibc 扩展(或等效功能)strftime
,则此方法有效。您可以通过调用 man strftime
. If it's not working on your platform, or you need to guarantee the behaviour cross-platform, then prefer to just make an extra function call here by using str.upper
as .
来检查
要添加 的答案,为了使其跨平台,额外的包装器是在所有平台上执行此操作的最准确方法。
Python 3+ 的包装示例将使用格式字符串:
import datetime
class dWrapper:
def __init__(self, date):
self.date = date
def __format__(self, spec):
caps = False
if '^' in spec:
caps = True
spec = spec.replace('^', '')
out = self.date.strftime(spec)
if caps:
out = out.upper()
return out
def __getattr__(self, key):
return getattr(self.date, key)
def parse(s, d):
return s.format(dWrapper(d))
d = datetime.datetime.now()
print(parse("To Upper doesn't work always {0:%d} of {0:%^B}, year {0:%Y}", d))
我设法在
之前得到了约会对象import datetime
getDate = datetime.date.today()
print(getDate.strftime("%Y-%B-%d"))
输出为 2018-June-23
但我想像这样格式化输出:2018-JUNE-23
(月份是大写的)
只需使用.upper()
:
print(getDate.strftime("%Y-%B-%d").upper())
要直接在格式字符串中执行此操作,请在月份 (^
) 前加上 carrot:
>>> getDate = datetime.date.today()
>>> print(getDate.strftime("%Y-%^B-%d"))
2018-JUNE-22
注意:如果您的平台上有可用的 glibc 扩展(或等效功能)strftime
,则此方法有效。您可以通过调用 man strftime
. If it's not working on your platform, or you need to guarantee the behaviour cross-platform, then prefer to just make an extra function call here by using str.upper
as
要添加
Python 3+ 的包装示例将使用格式字符串:
import datetime
class dWrapper:
def __init__(self, date):
self.date = date
def __format__(self, spec):
caps = False
if '^' in spec:
caps = True
spec = spec.replace('^', '')
out = self.date.strftime(spec)
if caps:
out = out.upper()
return out
def __getattr__(self, key):
return getattr(self.date, key)
def parse(s, d):
return s.format(dWrapper(d))
d = datetime.datetime.now()
print(parse("To Upper doesn't work always {0:%d} of {0:%^B}, year {0:%Y}", d))