1. 程式人生 > >Python時間,日期,時間戳之間轉換

Python時間,日期,時間戳之間轉換

clas mktime 指定日期 格式 日期格式 del 當前時間 格式轉換 other

#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

# 字符串格式更改如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"

# 方法二:
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)

  

Python時間,日期,時間戳之間轉換