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
相关产品推荐
相关产品推荐

