显示日期,如“May 5th",使用pythons strftime? [英] Display the date, like "May 5th", using pythons strftime?

查看:70
本文介绍了显示日期,如“May 5th",使用pythons strftime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way to do this?

推荐答案

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

strftime doesn't allow you to format a date with a suffix.

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

Here's a way to get the correct suffix:

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

在这里找到

将基于 Jochen 的评论的更紧凑的解决方案与 gsteff 的回答:

Combining a more compact solution based on Jochen's comment with gsteff's answer:

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())

给出:

2011 年 5 月 5 日

这篇关于显示日期,如“May 5th",使用pythons strftime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆