使用pythons strftime显示日期,例如“5月5日”? [重复]

问题描述 投票:0回答:5

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

在Python中,time.strftime可以很容易地生成像“Thursday May 05”这样的输出,但我想生成一个像“Thursday May 5th”这样的字符串(注意日期上额外的“th”)。最好的方法是什么?

python strftime
5个回答
104
投票

strftime
不允许您设置带后缀的日期格式。

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

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]

在这里找到

更新:

将基于 Jochen 评论的更紧凑的解决方案与 gsteff 的答案相结合

from datetime import datetime as dt

def suffix(d):
    return {1:'st',2:'nd',3:'rd'}.get(d%20, '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()))

给予:

May 5th, 2011


19
投票

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

#!/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()))

12
投票
"%s%s"%(day, 'trnshddt'[0xc0006c000000006c>>2*day&3::4])

但是说真的,这是特定于语言环境的,所以你应该在国际化过程中这样做


3
投票

from time import strftime

print strftime('%A %B %dth')

编辑:

看了各位高手的回答后更正:

from time import strftime

def special_strftime(dic = {'01':'st','21':'st','31':'st',
                            '02':'nd','22':'nd',
                            '03':'rd','23':'rd'}):
    x = strftime('%A %B %d')
    return x + dic.get(x[-2:],'th')


print special_strftime()

.

编辑2

还有:

from time import strftime


def special_strftime(dic = {'1':'st','2':'nd','3':'rd'}):

    x = strftime('%A %B %d')
    return x + ('th' if x[-2:] in ('11','12','13')
                else dic.get(x[-1],'th')

print special_strftime()

.

编辑3

最后可以简化一下:

from time import strftime

def special_strftime(dic = {'1':'st','2':'nd','3':'rd'}):

    x = strftime('%A %B %d')
    return x + ('th' if x[-2]=='1' else dic.get(x[-1],'th')

print special_strftime()

2
投票

你不能。

time.strftime
函数和
datetime.datetime.strftime
方法(通常)都使用平台 C 库的
strftime
函数,并且它(通常)不提供该格式。您需要使用第三方库,例如 dateutil

© www.soinside.com 2019 - 2024. All rights reserved.