python---time和datetime


#python中時間日期格式化符號

%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鍾數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天為星期的開始
%w 星期(0-6),星期天為星期的開始
%W 一年中的星期數(00-53)星期一為星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身

time模塊

時間相關操作,時間有三種表示方式:

  • 時間戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 結構化時間          元組包含了:年、日、星期等... time.struct_time    即:time.localtime()

time.time()

#返回當前時間的時間戳(1970紀元后經過的浮點秒數)。
#時間戳單位最適於做日期運算。但是1970年之前的日期就無法以此表示了。太遙遠的日期也不行,UNIX和Windows只支持到2038年。
>>> import time
>>> print(time.time())
1459999336.1963577

time.mktime(tupletime)

#接受時間元組並返回時間輟(1970紀元后經過的浮點秒數)。
#Python time.mktime() 函數執行與gmtime(), localtime()相反的操作,它接收struct_time對象作為參數,返回用秒數來表示時間的浮點數。
#如果輸入的值不是一個合法的時間,將觸發 OverflowError 或 ValueError。

#!/usr/bin/python3
import time
 
t = (2016, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )
print ("time.mktime(t) : %f" %  secs)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))
 
#以上實例輸出結果為:
time.mktime(t) : 1455699818.000000
asctime(localtime(secs)): Wed Feb 17 17:03:38 2016

time.gmtime([secs])

#接收時間輟(1970紀元后經過的浮點秒數)並返回格林威治天文時間下的時間元組t。注:t.tm_isdst始終為0
>>> import time
>>> print ("gmtime :", time.gmtime(1455508609.34375))
gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)

time.localtime([secs])

#接收時間輟(1970紀元后經過的浮點秒數)並返回當地時間下的時間元組t(t.tm_isdst可取0或1,取決於當地當時是不是夏令時)。
>>> import time
>>> print ("localtime(): ", time.localtime(1455508609.34375))
localtime():  time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)

time.mktime(tupletime)

#接受時間元組並返回時間輟(1970紀元后經過的浮點秒數)。
#Python time mktime() 函數執行與gmtime(), localtime()相反的操作,它接收struct_time對象作為參數,返回用秒數來表示時間的浮點數。
#如果輸入的值不是一個合法的時間,將觸發 OverflowError 或 ValueError。
#!/usr/bin/python3
import time
 
t = (2016, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )
print ("time.mktime(t) : %f" %  secs)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))
 
#以上實例輸出結果為:
time.mktime(t) : 1455699818.000000
asctime(localtime(secs)): Wed Feb 17 17:03:38 2016

time.strftime(fmt[,tupletime])

#接收以時間元組,並返回以可讀字符串表示的當地時間,格式由fmt決定。
 
>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016-04-07 11:18:05

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

#根據fmt的格式把一個時間字符串解析為時間元組。
>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("返回元組: ", struct_time)
返回元組:  time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

time.altzone

返回格林威治西部的夏令時地區的偏移秒數。如果該地區在格林威治東部會返回負值(如西歐,包括英國)。對夏令時啟用地區才能使用。
>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800

time.asctime([tupletime])

#接受時間元組並返回一個可讀的形式為"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18時07分14秒)的24個字符的字符串。
>>> import time
>>> t = time.localtime()
>>> print ("time.asctime(t): %s " % time.asctime(t))
time.asctime(t): Thu Apr  7 10:36:20 2016

time.clock()

#用以浮點數計算的秒數返回當前的CPU時間。用來衡量不同程序的耗時,比time.time()更有用。
#!/usr/bin/python3
import time
 
def procedure():
    time.sleep(2.5)
 
# time.clock
t0 = time.clock()
procedure()
print (time.clock() - t0)
 
# time.time
t0 = time.time()
procedure()
print (time.time() - t0)

#以上實例輸出結果為:
5.000000000000143e-05
2.5020556449890137

time.ctime([secs])

#作用相當於asctime(localtime(secs)),未給參數相當於asctime()
>>> import time
>>> print ("time.ctime() : %s" % time.ctime())
time.ctime() : Thu Apr  7 10:51:58 2016

time.sleep(secs)

#推遲調用線程的運行,secs指秒數。
#!/usr/bin/python3
import time
 
print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())

time.tzset()

根據環境變量TZ重新初始化時間相關設置。
標准TZ環境變量格式:
std offset [dst [offset [,start[/time], end[/time]]]]
''' 
參數:
std 和 dst:三個或者多個時間的縮寫字母。傳遞給 time.tzname.
offset: 距UTC的偏移,格式: [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}。
start[/time], end[/time]: DST 開始生效時的日期。格式為 m.w.d — 代表日期的月份、周數和日期。w=1 指月份中的第一周,而 w=5 指月份的最后一周。'start' 和 'end' 可以是以下格式之一:
    Jn: 儒略日 n (1 <= n <= 365)。閏年日(2月29)不計算在內。
    n: 儒略日 (0 <= n <= 365)。 閏年日(2月29)計算在內
    Mm.n.d: 日期的月份、周數和日期。w=1 指月份中的第一周,而 w=5 指月份的最后一周。
    time:(可選)DST 開始生效時的時間(24 小時制)。默認值為 02:00(指定時區的本地時間)。
'''

#!/usr/bin/python3
import time
import os
 
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print (time.strftime('%X %x %Z'))
 
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
time.tzset()
print (time.strftime('%X %x %Z'))
以上實例輸出結果為:
23:25:45 04/06/16 EDT
13:25:45 04/07/16 AEST

datetime模塊

datetime是Python處理日期和時間的標准庫

#獲取當前日期和時間

#第一種
import datetime

now = datetime.datetime.now()
print(now)

#第二種
from datetime import datetime

now = datetime.now()
print(now)

#獲取指定日期和時間
from datetime import datetime

dt = datetime(2015,3,9,12,21)
print(dt)
#輸出格式 2016-01-26
print(datetime.date.today()) 


#2016-01-16 將時間戳轉成日期格式
print(datetime.date.fromtimestamp(time.time()-864400) ) 

t = 1429417200.0
print(datetime.fromtimestamp(t))

current_time = datetime.datetime.now() #
print(current_time) #輸出2016-01-26 19:04:30.335935
print(current_time.timetuple()) #返回struct_time格式
   
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2014,9,12)) #輸出2014-09-12 19:06:24.074900,返回當前時間,但指定的值將被替換
   
str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #將字符串轉換成日期格式
new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比現在加10天
new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比現在減10天
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比現在減10小時
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比現在+120s
print(new_date)

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM