Python時間,字符串,時間戳之間轉換

1.將字符串的時間轉換爲時間戳

import time

        a = "2018-04-27 17:49:00"

#轉化爲數組

        timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")

     #轉換爲時間戳

     timeStamp = int(time.mktime(timeArray))#1524822540

2.字符串格式更改

    """

如a = "2018-04-27 17:49:00",想改爲 a = "2013/04/27 17:49:00"

     方法:先轉換爲時間數組,然後轉換爲其他格式

"""

import time

 a = "2018-04-27 17:49:00"

    timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")

    otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)#'2018/04/27 17:49:00'

3.時間戳轉換爲指定格式日期:

    方法一:

        利用localtime()轉換爲時間數組,然後格式化爲需要的格式,如

import time

        timeStamp = 1524822540

        timeArray = time.localtime(timeStamp)

        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)

        otherStyletime == "2018-04-27 17:49:00"

 

    方法二:

        import datetime

        timeStamp = 1524822540

        dateArray = datetime.datetime.utcfromtimestamp(timeStamp)

        otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")

        otherStyletime == "2018-04-27 17:49:00"

 

4.獲取當前時間並轉換爲指定日期格式

    方法一:

        import time

        #獲得當前時間時間戳

        now = int(time.time())  #這是時間戳

        #轉換爲其他日期格式,如:"%Y-%m-%d %H:%M:%S"

        timeArray = time.localtime(now)

        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)#2018-04-27 18:04:24

 

    方法二:

        import datetime

        #獲得當前時間

        now = datetime.datetime.now()  #這是時間數組格式

        #轉換爲指定的格式:

        otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")

 

5.獲得三天前的時間

    方法:

        import time

        import datetime

        #先獲得時間數組格式的日期

        threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))

        #轉換爲時間戳:

        timeStamp = int(time.mktime(threeDayAgo.timetuple()))

        #轉換爲其他字符串格式:

        otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")#2018-04-24 18:06:37

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

 

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

import datetime

    import time

    timeStamp = 1524822540

    #先轉換爲datetime

    dateArray = datetime.datetime.utcfromtimestamp(timeStamp)

    threeDayAgo = dateArray - datetime.timedelta(days = 3)
--------------------- 
作者:望月歸鄉 
來源:CSDN 
原文:https://blog.csdn.net/sinat_32546159/article/details/78850479 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

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