使用pythons strftime显示日期,如"5月5日"?

But*_*840 22 python strftime

可能重复:
Python:日期序数输出?

在Python中,time.strftime可以很容易地产生类似"星期四5月05"的输出,但是我想生成一个像"星期四5月5日"这样的字符串(注意日期的附加"th").做这个的最好方式是什么?

Aco*_*orn 58

strftime 不允许您使用后缀格式化日期.

这是获得正确后缀的方法:

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]
Run Code Online (Sandbox Code Playgroud)

在这里找到

更新:

结合基于Jochen评论的更紧凑的解决方案和gsteff的答案:

from datetime import datetime as dt

def suffix(d):
    return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')

def custom_strftime(format, t):
    return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))

print custom_strftime('%B {S}, %Y', dt.now())
Run Code Online (Sandbox Code Playgroud)

得到:

May 5th, 2011

  • `suffix = {1:"st",2:"nd",3:"rd"} .get(day%10,"th")` (5认同)
  • @Jochen Ritzel - 这看起来更聪明,但是一旦 5 月 11 日(5 月 11 日)到来会发生什么? (2认同)

gst*_*eff 14

这似乎添加了适当的后缀,并删除了天数中丑陋的前导零:

#!/usr/bin/python

import time

day_endings = {
    1: 'st',
    2: 'nd',
    3: 'rd',
    21: 'st',
    22: 'nd',
    23: 'rd',
    31: 'st'
}

def custom_strftime(format, t):
    return time.strftime(format, t).replace('{TH}', str(t[2]) + day_endings.get(t[2], 'th'))

print custom_strftime('%B {TH}, %Y', time.localtime())
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 9

"%s%s"%(day, 'trnshddt'[0xc0006c000000006c>>2*day&3::4])
Run Code Online (Sandbox Code Playgroud)

但严重的是,这是特定于语言环境的,因此您应该在国际化期间这样做

  • `0xc0006c000000006c >> 2*day&3`部分从相应日的位字段中查找2位(提示:尝试`bin(0xc0006c000000006c)`,最后2位是第0天,10以上的日都是0).然后它将第0个字符串的索引作为0-3,并跳过4个字符以获取第2个字符. (3认同)
  • @Roy,你错过了最后一句话吗?这里所有的硬编码答案都是“错误的”。做这些事情的正确位置是在 i18n 库中 (2认同)