python datetime模块使用
datetime模块中包含了3个类,分别是date, time, datetime.
datetime.date表示日期的类,属性有year, month, day.
datetime.time表示时间的类, 属性有hour, minute, second, microsecond;
datetime.datetime表示日期时间.
1:date类:
1 date = datetime.date(2019, 6, 14)
2 print(date)
3 print("{0}-{1}-{2}".format(date.year, date.month. date.day))
4 # 打印结果:2019-06-14
5 # 打印结果:2019-6-14
6
7 today = datetime.date.today() # 返回当天的日期
8 print(today)
9 # 打印结果:2019-06-14
formattimestamp()传入一个时间戳,返回一个date对象,例如:
1 import time
2 import datetime
3 time = time.time()
4 today = datetime.date.fromtimestamp(time)
5 print(today)
6 # 打印结果:2019-06-14
strftime格式化,例如:
1 import datetime
2 today = datetime.date.today().strftime('%Y%m%d')
3 print(today)
4 # 打印结果:20190614
1 import datetime
2 # 在当天的天数上边加上3天.
3 day = datetime.date.today()+datetime.timedelta(3)
4 print(day)
5 # 打印结果:2019-06-17
2:time类:
time方法主要用于时间的操作:
1 import datetime
2 formatTime = datetime.time(10,10,30).strftime("%H-%M-%S")
3 print(formatTime)
4 # 打印结果:10-10-30
3:datetime 类:
datetime大部分属性和方法都是继承于date和time类.
import datetime
formatTime = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
print(formatTime)
# 打印结果:2019-06-14 14:34:25