Python時間,日期,時間戳之間轉換,時間轉換時間戳,Python時間戳轉換時間,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
#一行代碼的寫法是
timeStamp = int(time.mktime(time.strptime(a, "%Y-%m-%d %H:%M:%S")))
# 字符串格式更改如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"
#一行代碼的寫法
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(timeStamp))
# 方法二:
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"

# 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")

# 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")
# 注:timedelta()的參數有:days, hours, seconds, microseconds

# 6.給定時間戳, 計算該時間的幾天前時間:
timeStamp = 1381419600
# 先轉換爲datetime
import datetime
import time

dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days=3)

  注意事項: 1.Python的時間戳長度是10個數字,Java的長度是13個數字。咱們在作時間戳轉換的時候能夠 乘以一千或者除以一千html

        2. Python 中的 %Y-%m-%d %H:%M:%S 能夠根據本身的須要進行修改python

 

本文連接:http://www.cnblogs.com/xuchunlin/p/6946666.html 數組