時間函數 python

1.將字符串的時間轉換爲時間戳
    方法:
        a = "2013-10-10 23:40:00"
        將其轉換爲時間數組
        import time
        timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
    轉換爲時間戳:
    timeStamp = int(time.mktime(timeArray))
    timeStamp == 1381419600
2.字符串格式更改
    如a = "2013-10-10 23:40:00",想改成 a = "2013/10/10 23:40:00"
    方法:先轉換爲時間數組,而後轉換爲其餘格式
    timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
    otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)數組


3.時間戳轉換爲指定格式日期:
    方法一:
        利用localtime()轉換爲時間數組,而後格式化爲須要的格式,如
        timeStamp = 1381419600
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        otherStyletime == "2013-10-10 23:40:00"spa

    方法二:
        import datetime
        timeStamp = 1381419600
        dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
        otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
        otherStyletime == "2013-10-10 23:40:00"
        注意:使用此方法時必須先設置好時區,不然有時差code

4.獲取當前時間並轉換爲指定日期格式
    方法一:
        import time
        得到當前時間時間戳
        now = int(time.time())  ->這是時間戳
        轉換爲其餘日期格式,如:"%Y-%m-%d %H:%M:%S"
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)對象

    方法二:
        import datetime
        得到當前時間
        now = datetime.datetime.now()  ->這是時間數組格式
        轉換爲指定的格式:
        otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")three

5.得到三天前的時間
方法:字符串

  1.  
             import time
  2.  
             import datetime
  3.  
            先得到時間數組格式的日期
  4.  
            threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
  5.  
            轉換爲時間戳:
  6.  
                timeStamp = int(time.mktime(threeDayAgo.timetuple()))
  7.  
            轉換爲其餘字符串格式:
  8.  
                otherStyleTime = threeDayAgo.strftime( "%Y-%m-%d %H:%M:%S")


注:timedelta()的參數有:days,hours,seconds,microsecondsstring

6.給定時間戳,計算該時間的幾天前時間:
 class

  1.  
        timeStamp = 1381419600
  2.  
        先轉換爲datetime
  3.  
         import datetime
  4.  
         import time
  5.  
        dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
  6.  
        threeDayAgo = dateArray - datetime.timedelta(days = 3)


 參考5,能夠轉換爲其餘的任意格式了    
    
7. 給定日期字符串,直接轉換爲datetime對象效率

  1.  
        dateStr = '2013-10-10 23:40:00'
  2.  
        datetimeObj = datetime.datetime.strptime(dateStr, "%Y-%m-%d %H:%M:%S")

        注:將字符串日期轉換爲datetime後能夠很高效的進行統計操做,由於轉換爲datetime後,
           能夠經過datetime.timedelta()方法來先後移動時間,效率很高,並且可讀性很強。import

8.計算兩個datetime之間的差距
 

    1.  
             a = datetime.datetime( 2014,12,4,1,59,59)
    2.  
             b = datetime.datetime( 2014,12,4,3,59,59)
    3.  
             diffSeconds = (b-a).total_seconds()
相關文章
相關標籤/搜索