time
>>> import time >>> time.localtime() #以time.struct_time类型,打印本地时间 time.struct_time(tm_year=2018, tm_mon=9, tm_mday=10, tm_hour=11, tm_min=1, tm_sec=45, tm_wday=0, tm_yday=253, tm_isdst=0) >>> time.time() #返回当前时间戳 1536548528.335637 >>> time.ctime() #返回当前时间 'Mon Sep 10 11:02:24 2018' >>> time.ctime(time.time()-86400) #返回一天前的时间 'Sun Sep 9 11:02:59 2018' >>> time.gmtime() #以time.struct_time类型,打印本地时间 time.struct_time(tm_year=2018, tm_mon=9, tm_mday=10, tm_hour=3, tm_min=3, tm_sec=32, tm_wday=0, tm_yday=253, tm_isdst=0) >>> time.mktime(time.gmtime()) #转换成时间戳 1536519875.0 >>> time.strftime('%a %b %d %H:%M:%S %Y', time.localtime()) #本地时间 'Mon Sep 10 11:01:28 2018' >>> time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) #打印UTC,世界标准时间,北京时区是东八区,领先UTC八个小时 '2018-09-10 03:04:53' >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) #本地时间 '2018-09-10 11:05:02' >>> time.mktime(time.strptime("2018-09-10 15:06:33","%Y-%m-%d %H:%M:%S")) 把time.struct_time类型时间,转换成时间戳 1536563193.0
图片来源:https://www.cnblogs.com/cq146637/p/8205054.html
datetime
>>> import datetime
>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #获取当前时间 '2018-09-10 11:17:30' >>> datetime.date.today() #获取年,月,日 datetime.date(2018, 9, 10) >>> datetime.datetime.now() #打印当前时间,精确到微秒 datetime.datetime(2018, 9, 10, 11, 18, 0, 691264) >>> datetime.timedelta(days=1) #不加参数是00:00,参数days=1表示一天: datetime.timedelta(1) >>> datetime.date.today()-datetime.timedelta(days=1) #获取昨天日期 datetime.date(2018, 9, 9) >>> datetime.datetime.now() - datetime.timedelta(days=1) #获取昨天的精确日期 datetime.datetime(2018, 9, 9, 11, 20, 11, 108946)
>>> datetime.datetime.now().timetuple() #转成time.struct_time格式时间 time.struct_time(tm_year=2018, tm_mon=9, tm_mday=10, tm_hour=11, tm_min=21, tm_sec=33, tm_wday=0, tm_yday=253, tm_isdst=-1) >>> datetime.datetime.now() +datetime.timedelta(days=10) #加十天 datetime.datetime(2018, 9, 20, 11, 21, 43, 39543) >>> datetime.datetime.now() +datetime.timedelta(days=-10) #减十天 datetime.datetime(2018, 8, 31, 11, 21, 49, 789403) >>> datetime.datetime.now() +datetime.timedelta(hours=-10) #减十个小时 datetime.datetime(2018, 9, 10, 1, 21, 56, 24417) >>> datetime.datetime.now() +datetime.timedelta(seconds=120) #加120s datetime.datetime(2018, 9, 10, 11, 24, 4, 249736) >>> datetime.datetime.now().replace(2014,9,12) #替换成指定的时间 datetime.datetime(2014, 9, 12, 11, 22, 28, 541687) >>> datetime.datetime.strptime("21/11/06 16:30","%d/%m/%y %H:%M") #格式化输出 datetime.datetime(2006, 11, 21, 16, 30) >>> datetime.datetime.now() > datetime.datetime.now().replace(2018,5) #对比时间大小,取指定时间范围使用 True