1、获取时间需要引入时间库
import time,datetime
localtime = time.localtime(time.time())
print("current Time:",locaitime)
time.struct_time 属于struct_time元组,struct_time元组具有如下属性:
2、获取格式化时间
最简单的获取格式化的方法是 asctime()
a) 日期转换为字符串
#首选
print(time.strftime('%Y-%m-%d %H:%M:%S'))
#其次
print(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S'))
#最后
print(str(datetime.datetime.now())[:19])
b)字符串转换为日期
expire_time="2019-02-24 09:09:09"
d=datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
print(d)
c)获取时间差
oneday = datetime.timedelta(days=1)
#今天,2019-02-24
today = datetime.date.today()
#昨天,2019-02-23
yesterday = datetime.date.today() - oneday
#明天,2019-02-25
tomorrow = datetime.date.today() + oneday
#获取今天零点的时间,2019-02-25 00:00:00
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')
#0:00:00.001000
print datetime.timedelta(milliseconds=1), #1毫秒
#0:00:01
print datetime.timedelta(seconds=1), #1秒
#0:01:00
print datetime.timedelta(minutes=1), #1分钟
#1:00:00
print datetime.timedelta(hours=1), #1小时
#1 day, 0:00:00
print datetime.timedelta(days=1), #1天
#7 days, 0:00:00
print datetime.timedelta(weeks=1)
d)根据时间差获取日期
#1 day, 0:00:00
oneday = datetime.timedelta(days=1)
#今天,2019-02-25 16:07:23.943000
today_time = datetime.datetime.now()
#昨天,2019-02-25 16:07:23.943000
yesterday_time = datetime.datetime.now() - oneday
#明天,2019-02-25 16:07:23.943000
tomorrow_time = datetime.datetime.now() + oneday
#注意时间是浮点数,带毫秒。
#那么要获取当前时间,需要格式化一下:
print (datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S'))
print (datetime.datetime.strftime(yesterday_time, '%Y-%m-%d %H:%M:%S'))
print (datetime.datetime.strftime(tomorrow_time, '%Y-%m-%d %H:%M:%S'))
3、获取上个月最后一天
last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
4、字符串格式日期转化为秒数,浮点类型
expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
time_sec_float = time.mktime(d.timetuple())
print (time_sec_float)
5、秒数转为字符串
time_sec = time.time()
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec)))
好记性不如烂笔头,记得多掌握的越多。