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)
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志