Python datetime 模块

Python strftime() 函数用于按格式码把时间格式化成字符串

语法

dt.strftime(format)

参数

format:格式字符串,如 "%Y-%m-%d"

返回值

返回按格式码格式化后的字符串 str

示例

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d"))          # 2024-01-15
print(now.strftime("%Y/%m/%d %H:%M"))    # 2024/01/15 10:30
print(now.strftime("%A"))                # Monday
print(now.strftime("%B %d, %Y"))         # January 15, 2024
print(now.strftime("%H:%M:%S"))          # 10:30:45

常用格式码:%Y 年份、%m 月份、%d 日期、%H 时、%M 分、%S 秒、%A 星期。

注意事项

strftime 的 f 是 format(输出)。解析输入用 strptime(p 是 parse)。