1. 程式人生 > >python中時間、日期、時間戳之間的轉換

python中時間、日期、時間戳之間的轉換

一、將字串轉換為時間戳

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import time
tm = "2013-10-10 23:40:00"
#將其轉換為時間陣列
timeArray = time.strptime(tm, "%Y-%m-%d %H:%M:%S")
#轉換為時間戳:
timeStamp = int(time.mktime(timeArray))
print timeStamp
輸出結果: 1381419600

二、字串格式的更改

如:把"2013-10-10 23:40:00",改為"2013/10/10 23:40:00"

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import time
# 先轉換為時間陣列,然後轉換為其他格式
tm = "2013-10-10 23:40:00"
timeArray = time.strptime(tm, "%Y-%m-%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print otherStyleTime
輸出結果: 2013/10/10 23:40:00

三、時間戳轉換為指定格式日期

方法一:

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import 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

方法二:

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import time
import datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print otherStyleTime
輸出結果:2013-10-10 15:40:00

四、獲取當前時間並轉換為指定日期格式

方法一:

#-*- coding: utf-8 -*-
__author__ = 'Sky'
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)
print otherStyleTime
輸出結果:2016-03-06 19:16:26

方法二:

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import time
import datetime
#獲得當前時間
now = datetime.datetime.now()  #時間陣列格式
#轉換為指定的格式:
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print otherStyleTime

輸出結果:2016-03-06 19:19:41

五、獲得三天前的時間

#-*- coding: utf-8 -*-
__author__ = 'Sky'
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")
print otherStyleTime
輸出結果:2016-03-03 19:22:33

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

六、給定時間戳,計算該時間的幾天前時間

#-*- coding: utf-8 -*-
__author__ = 'Sky'
import time
import datetime
timeStamp = 1381419600
#先轉換為datetime
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
print threeDayAgo
輸出結果:2013-10-07 15:40:00