python datetime模块

python datetime模块使用

datetime模块中包含了3个类,分别是date, time, datetime.
datetime.date表示日期的类,属性有year, month, day.
datetime.time表示时间的类, 属性有hour, minute, second, microsecond;
datetime.datetime表示日期时间.
1:date类:
date = datetime.date(2019, 6, 14)
print(date)
print("{0}-{1}-{2}".format(date.year, date.month. date.day))
# 打印结果:2019-06-14
# 打印结果:2019-6-14

today = datetime.date.today() # 返回当天的日期
print(today)
# 打印结果:2019-06-14

formattimestamp()传入一个时间戳,返回一个date对象,例如:

import time
import datetime
time = time.time()
today = datetime.date.fromtimestamp(time)
print(today)
# 打印结果:2019-06-14

strftime格式化,例如:

import datetime
today = datetime.date.today().strftime('%Y%m%d')
print(today)
# 打印结果:20190614

timedelta() 对天数进行操作:

import datetime
# 在当天的天数上边加上3天.
day = datetime.date.today()+datetime.timedelta(3)
print(day)
# 打印结果:2019-06-17
2:time类:

time方法主要用于时间的操作:

import datetime
formatTime = datetime.time(10,10,30).strftime("%H-%M-%S")
print(formatTime)
# 打印结果: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

你可能感兴趣的:(python)