答案:Python的time模块通过strftime和strptime实现时间格式转换,常用格式符包括%Y、%m、%d等,分别用于年、月、日的表示,结合format字符串可完成结构化时间与字符串的相互转换。
在 Python 的 time 模块中,时间格式主要通过字符串与时间结构之间的转换来实现。常用的核心函数是 time.strftime() 和 time.strptime(),它们都依赖于格式化字符串来定义时间的表示方式。
以下是在 time.strftime(format, struct_time) 和 time.strptime(string, format) 中常用的格式符号:
使用 time.strftime() 可以将 struct_time 对象格式化为可读字符串。
import time
current = time.localtime() # 获取当前时间的结构化表示
formatted = time.strftime("%Y-%m-%d %H:%M:%S", current)
print(formatted) # 输出类似:2025-04-05 14:30:25
使用 time.strptime() 可以将时间字符串解析成 struct_time 对象。
import time date_str = "2025-04-05 14:30:25" parsed = time.strptime(date_str, "%Y-%m-%d %H:%M:%S") print(parsed) # 输出 struct_time 对象,包含年月日时分秒等字段
一些实用的时间格式组合:
"%Y-%m-%d" → 2025-04-05"%H:%M:%S" → 14:30:25"%Y年%m月%d日" → 2025年04月05日(中文环境可用)"%a, %b %
d %Y" → Fri, Apr 05 2025"%Y-%m-%d %A" → 2025-04-05 Friday基本上就这些。掌握这些格式代码后,就可以灵活地处理时间字符串和结构化时间之间的转换了。注意格式字符串必须与输入或期望输出完全匹配,否则会报错。