Python日期时间对象的基本用法

示例

datetime模块包含三种主要类型的对象-日期,时间和日期时间。

import datetime

# 日期对象
today = datetime.date.today()
new_year = datetime.date(2017, 01, 01) #datetime.date(2017,1,1)

# 时间对象
noon = datetime.time(12, 0, 0) #datetime.time(12,0)

# 当前日期时间
now = datetime.datetime.now()

# 日期时间对象
millenium_turn = datetime.datetime(2000, 1, 1, 0, 0, 0) #datetime.datetime(2000,1,1,0,0)

仅在相同数据类型内支持对这些对象的算术运算,并且对不同类型的实例执行简单算术将导致TypeError。

# 从今天中午开始减去
noon-today
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.date'
However, it is straightforward to convert between types.

# 改为这样做
print('Time since the millenium at midnight: ',
      datetime.datetime(today.year, today.month, today.day) - millenium_turn)

# 或这个
print('Time since the millenium at noon: ',
      datetime.datetime.combine(today, noon) - millenium_turn)