python常用的日期时间模块
生活随笔
收集整理的這篇文章主要介紹了
python常用的日期时间模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天、昨天、明天
import datetime today = datetime.date.today() # 今天 yesterday = today - datetime.timedelta(days=1) # 昨天 tomorrow = today + datetime.timedelta(days=1) # 明天時間提起之間轉化
引入模塊
# 引入模塊 import time, datetime1、 str類型的日期轉換為時間戳
# 字符類型的時間tss1 = '2013-10-10 23:40:00'# 轉為時間數組timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")print timeArray # timeArray可以調用tm_year等print timeArray.tm_year # 2013# 轉為時間戳timeStamp = int(time.mktime(timeArray))print timeStamp # 1381419600# 結果如下time.struct_time(tm_year=2013, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=283, tm_isdst=-1)15 201316 13814196002 更改str類型日期的顯示格式
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' tss2 = "2013-10-10 23:40:00" # 轉為數組 timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S") # 轉為其它顯示格式 otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) print otherStyleTime # 2013/10/10 23:40:00tss3 = "2013/10/10 23:40:00" timeArray = time.strptime(tss3, "%Y/%m/%d %H:%M:%S") otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print otherStyleTime # 2013-10-10 23:40:003 時間戳轉換為指定格式的日期
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' # 使用time timeStamp = 1381419600 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) print(otherStyleTime) # 2013--10--10 23:40:00 # 使用datetime timeStamp = 1381419600 dateArray = datetime.datetime.fromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S") print(otherStyleTime) # 2013--10--10 23:40:00 # 使用datetime,指定utc時間,相差8小時 timeStamp = 1381419600 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S") print(otherStyleTime) # 2013--10--10 15:40:004 獲取當前時間并且用指定格式顯示
# time獲取當前時間戳 now = int(time.time()) # 1533952277 timeArray = time.localtime(now) print timeArray otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) print otherStyleTime# 結果如下 time.struct_time(tm_year=2018, tm_mon=8, tm_mday=11, tm_hour=9, tm_min=51, tm_sec=17, tm_wday=5, tm_yday=223, tm_isdst=0) 2018--08--11 09:51:17# datetime獲取當前時間,數組格式 now = datetime.datetime.now() print now otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S") print otherStyleTime# 結果如下: 2018-08-11 09:51:17.362986 2018--08--11 09:51:17總結
以上是生活随笔為你收集整理的python常用的日期时间模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python教程:collections
- 下一篇: Python scrapy 命令行传参