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

你可能感兴趣的:(Python)