10.8. 日期和时间

datetime 模块提供了以简单和复杂的方式操作日期和时间的类。虽然支持日期和时间算法,但实现的重点是有效的成员提取以进行输出格式化和操作。该模块还支持可感知时区的对象。

  1. >>> # dates are easily constructed and formatted
  2. >>> from datetime import date
  3. >>> now = date.today()
  4. >>> now
  5. datetime.date(2003, 12, 2)
  6. >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
  7. '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
  8.  
  9. >>> # dates support calendar arithmetic
  10. >>> birthday = date(1964, 7, 31)
  11. >>> age = now - birthday
  12. >>> age.days
  13. 14368