相比于time模块,datetime模块的接口则更直观、更容易调用
datetime模块定义了下面这几个类:
- datetime.date:表示日期的类。常用的属性有year, month, day;
- datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
- datetime.datetime:表示日期时间。
- datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
- datetime.tzinfo:与时区有关的相关信息。
代码示例:
import datetime, time print(datetime.datetime.now()) # 2018-11-21 17:29:36.137516 a = datetime.datetime.now() print(a.year, a.month, a.day) # 2018 11 21 print(time.time()) # 1542792640.978857 # 把时间戳转换成年月日,比time()里的方法简单 print(datetime.date.fromtimestamp(time.time())) # 2018-11-21 b = datetime.date.fromtimestamp(time.time()) print(b.timetuple()) # 转成时间对象,但是把小时、分钟、秒丢了.因为上面转换的时候把小时、分钟、秒丢失了。 # 用datetime进行时间的运算 print(datetime.timedelta(5)) # 5 days, 0:00:00 #也有别的参数,如:hours=3 ,minutes=10,seconds=20 print(b - datetime.timedelta(5)) # 2018-11-16 也可以加 # 时间的替换 print(b.replace(year=2016, month=8, day=10)) # 2016-08-10