python之time和datetime的常用方法

來源:互聯網
上載者:User

標籤:字串格式化   mkt   range   sleep   mon   amp   for   擷取   方式   

一、time的常用方法:

import time,datetime

# 時間有三種展現方式:時間戳記,時間元組,格式化的時間
print(time.time())#目前時間戳
print(int(time.time()))
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘))#格式化的時間
print(time.strftime(‘%Y-%m-%d‘))
print(time.strftime(‘%H:%M:%S‘))
print(time.gmtime())#擷取標準時區的時間元組,如果傳入了時間戳記,就是把時間戳記轉換成時間元組
print(time.gmtime(1516194265))

執行結果:

1516197631.0563018
1516197631
2018-01-17 22:00:31
2018-01-17
22:00:31
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=14, tm_min=0, tm_sec=31, tm_wday=2, tm_yday=17, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=13, tm_min=4, tm_sec=25, tm_wday=2, tm_yday=17, tm_isdst=0)

二、 datetime常用方法:

# 使用datetime和time擷取目前時間
now1 = datetime.datetime.now()
now2=time.strftime(‘%Y-%m-%d %H:%M:%S‘)
print(now1)
print(now2)
now = datetime.datetime.now()
d1 = now - datetime.timedelta(hours=1)#擷取前一小時
d2 = now - datetime.timedelta(days=1)#擷取前一天
print(now)
print(d1)

執行結果:

2018-01-17 22:03:04.686923
2018-01-17 22:03:04
2018-01-17 22:03:04.687486
2018-01-17 21:03:04.687486

三、使用datetime擷取代碼執行的時間長度

# 使用時間戳擷取代碼執行時間
s_time = time.time()
for i in range(0,10):
time.sleep(1)
e_time=time.time()
print(‘代碼已耗用時間是:‘,e_time - s_time)

執行結果:

代碼已耗用時間是: 10.003105163574219

四、時間戳記和字串的互相轉化

# 字串格式化時間轉換時間戳記
str_time = ‘2018-1-17‘
print(time.mktime(time.strptime(str_time,‘%Y-%m-%d‘)))

# 時間戳記轉換成格式化的時間字串
gsh_time= time.time()
print(time.strftime(‘%Y-%m-%d‘,time.localtime(gsh_time)))

# datetime對象轉換成時間戳記
dt = datetime.datetime.now()
print(time.mktime(dt.timetuple()))

# 時間戳記轉換成datetime對象
sjc_time = time.time()
print(datetime.datetime.fromtimestamp(sjc_time))

執行結果:

1516118400.0
2018-01-17
1516198008.0
2018-01-17 22:06:48.944055

 

python之time和datetime的常用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.