time & datetime

時間相關的操做,時間有三種表示方式:python

  • 時間戳               1970年1月1日以後的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 結構化時間          元組包含了:年、日、星期等... time.struct_time    即:time.localtime()
print(time.gmtime())    #可加時間戳參數,將一個時間戳轉換爲UTC時區(0時區)的struct_time.其默認值爲time.time(),函數返回time.struct_time類型的對象。(struct_time是在time模塊中定義的表示時間的對象)
print(time.localtime()) #可加時間戳參數,做用是格式化時間戳爲本地的時間
print(time.strptime('2014-11-11', '%Y-%m-%d')) #字符串轉換成time.struct格式
例:
print(time.strptime('2016-7-18','%Y-%m-%d'))

  time.struct_time(tm_year=2016, tm_mon=7, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=200, tm_isdst=-1)app

   
print(time.strftime('%Y-%m-%d')) #默認當前時間
print(time.strftime('%Y-%m-%d',time.localtime())) #默認當前時間
print(time.asctime())   #返回一個可讀的形式爲"Tue Dec 11 18:07:14 2008"(2008年12月11日 週二18時07分14秒)的24個字符的字符串。
print(time.asctime(time.localtime()))
print(time.ctime(time.time()))  #把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式
   
from datetime import date,datetime 

'''
datetime.date:表示日期的類。經常使用的屬性有year, month, day
datetime.time:表示時間的類。經常使用的屬性有hour, minute, second, microsecond
datetime.datetime:表示日期時間
datetime.timedelta:表示時間間隔,即兩個時間點之間的長度,直屬datetime類
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
strftime("%Y-%m-%d")
'''

print(datetime.now())  #返回新的時間對象
	例:
  In [10]: datetime.now()
  Out[10]: datetime.datetime(2016, 6, 22, 9, 43, 4, 625646)

print(date.weekday(datetime.now()))  #星期幾 星期一 到 星期六 對應 0-6
	例:
	In [13]: date.weekday(datetime.now())
	Out[13]: 2

print(datime.today().day) #今天幾號
print(datetime.datetime.now() - datetime.timedelta(days=5)) #時間減法
  
(datetime.datetime.now()-datetime.timedelta(days=30)).strftime("%Y-%m-%d") #時間減法 strftime 爲可讀字串
  例:

    In [43]: (datetime.datetime.now()-datetime.timedelta(days=30)).strftime("%Y-%m-%d")
    Out[43]: '2016-05-23'函數

  

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
相關文章
相關標籤/搜索