【发布时间】:2018-12-02 07:09:02
【问题描述】:
我设法得到日期
import datetime
getDate = datetime.date.today()
print(getDate.strftime("%Y-%B-%d"))
输出为2018-June-23
但我想像这样格式化输出:2018-JUNE-23(月份是大写)
【问题讨论】:
标签: python python-3.x strftime
我设法得到日期
import datetime
getDate = datetime.date.today()
print(getDate.strftime("%Y-%B-%d"))
输出为2018-June-23
但我想像这样格式化输出:2018-JUNE-23(月份是大写)
【问题讨论】:
标签: python python-3.x strftime
补充wim 的答案,为了使其跨平台,额外的包装器是在所有平台上执行此操作的最准确方法。
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))
【讨论】:
只需使用.upper():
print(getDate.strftime("%Y-%B-%d").upper())
【讨论】:
要直接在格式字符串中执行此操作,请在月份前添加 carrot (^):
>>> getDate = datetime.date.today()
>>> print(getDate.strftime("%Y-%^B-%d"))
2018-JUNE-22
注意: 如果您的平台 strftime 上有可用的 glibc 扩展(或等效功能),则此方法有效。您可以致电man strftime 进行检查。如果它不能在您的平台上运行,或者您需要保证跨平台的行为,那么更愿意在这里使用str.upper 作为shown in the other answer 进行额外的函数调用。
【讨论】: