python中的time和datetime的常用方法

 一、time的常用方法:

#coding=utf-8
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))

執行結果:

二、 datetime常用方法:

#coding=utf-8
import time, 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)

執行結果:

三、時間戳和字符串的互相轉化

#coding=utf-8
import time, datetime

# 字符串格式化時間轉換時間戳
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))

執行結果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章