You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现自定义datetime格式为02FEB2021 00:00:00的样式?

Python生成指定格式日期的实现方法

可以直接使用Python标准内置的datetime模块实现需求,无需引入第三方依赖,具体实现逻辑如下:

  • 目标格式拆分:两位日期 + 全大写英文月份简写 + 四位年份 + 时分秒,对应strftime格式符分别为%d(两位日)、%b(英文月份简写)、%Y(四位年)、%H:%M:%S(24小时制时分秒),最终将生成的字符串转为全大写即可匹配要求。

代码示例

示例1:生成指定日期(2021年2月2日0点)的目标格式

from datetime import datetime

custom_date = datetime(2021, 2, 2, 0, 0, 0)
result = custom_date.strftime("%d%b%Y %H:%M:%S").upper()
print(result)
# 输出结果:02FEB2021 00:00:00

示例2:生成当前时间的目标格式

from datetime import datetime

current = datetime.now()
result = current.strftime("%d%b%Y %H:%M:%S").upper()
print(result)

非英文系统适配

如果你的操作系统默认语言不是英文,%b会输出本地语言的月份简写,可临时指定英文时间locale解决:

from datetime import datetime
import locale

# 临时设置时间相关locale为英文,Windows系统可替换为'en_US'
locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')
custom_date = datetime(2021, 2, 2, 0, 0, 0)
result = custom_date.strftime("%d%b%Y %H:%M:%S").upper()
print(result)

内容的提问来源于stack exchange,提问作者meteorolog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:07