← 中文资源

简体中文版本

strptime 按格式指令解析日期

strptime 按格式指令逐字解析固定布局的日期字符串,不匹配就抛 ValueError;配 timedelta 做截止时间运算,strftime 反向格式化输出。

阅读英文原文

实现说明

顶层就这几处状态:stamp、deploy、deadline。

使用要点

  • 跑完文件,输出里会留下标记——parsed:、rejected:、deadline:。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 全部导入都来自标准库:datetime。 文件的状态由几个模块级绑定持有:stamp、deploy、deadline。

核心语句

except ValueError as exc:
    print("rejected:", exc)

代码示例

from datetime import datetime, timedelta

stamp = "2026-11-14T09:30:00"
deploy = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%S")
print("parsed:", deploy.year, deploy.month, deploy.day, deploy.hour)

# the format must match the string character for character: a wrong order raises ValueError
try:
    datetime.strptime("14/11/2026", "%Y-%m-%d")
except ValueError as exc:
    print("rejected:", exc)

# after parsing you are in datetime land: timedelta arithmetic plus strftime for the reverse direction
deadline = deploy + timedelta(days=2, hours=6)
print("deadline:", deadline.strftime("%Y-%m-%d %H:%M"))
print("gap hours:", (deadline - deploy).total_seconds() / 3600)