9.1、獲取當(dāng)前時(shí)間,例如:
import time, datetime;
localtime = time.localtime(time.time())
#Local current time : time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0) print "Local current time :", localtime 說明:time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0)屬于struct_time元組,struct_time元組具有如下屬性:
9.2、獲取格式化的時(shí)間
可以根據(jù)需求選取各種格式,但是最簡單的獲取可讀的時(shí)間模式的函數(shù)是asctime(): 2.1、日期轉(zhuǎn)換為字符串
首選: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]
2.2、字符串轉(zhuǎn)換為日期
expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S") print d;
9.3、獲取日期差
oneday = datetime.timedelta(days=1)
#今天,2014-03-21 today = datetime.date.today() #昨天,2014-03-20 yesterday = datetime.date.today() - oneday #明天,2014-03-22 tomorrow = datetime.date.today() + oneday #獲取今天零點(diǎn)的時(shí)間,2014-03-21 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小時(shí) #1 day, 0:00:00 print datetime.timedelta(days=1), #1天 #7 days, 0:00:00 print datetime.timedelta(weeks=1)
9.4、獲取時(shí)間差
#1 day, 0:00:00
oneday = datetime.timedelta(days=1) #今天,2014-03-21 16:07:23.943000 today_time = datetime.datetime.now() #昨天,2014-03-20 16:07:23.943000 yesterday_time = datetime.datetime.now() - oneday #明天,2014-03-22 16:07:23.943000 tomorrow_time = datetime.datetime.now() + oneday 注意時(shí)間是浮點(diǎn)數(shù),帶毫秒。 那么要獲取當(dāng)前時(shí)間,需要格式化一下: 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')
9.5、獲取上個(gè)月最后一天
last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
9.6、字符串日期格式化為秒數(shù),返回浮點(diǎn)類型:
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
9.7、日期格式化為秒數(shù),返回浮點(diǎn)類型:
d = datetime.date.today()
time_sec_float = time.mktime(d.timetuple()) print time_sec_float
9.8、秒數(shù)轉(zhuǎn)字符串
time_sec = time.time()
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec)) |
|