ayuLiao
5/5/2018 - 7:56 AM

python时间操作

python操作时间,对时间进行格式化、计算和比较

# 时间字符串转时间戳
import time

# 格式化时间
format_time = '2017-03-16 18:22:06'

# 时间
ts = time.strptime(format_time, "%Y-%m-%d %H:%M:%S")
// time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=18, tm_min=35, tm_sec=10, tm_wday=3, tm_yday=75, tm_isdst=0)

# 格式化时间转时间戳
time.mktime(ts)
// 1489660028.0


# 时间戳转换为指定格式日期
import time

timeStamp = 1381419600

t =time.localtime(timeStamp)

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

In [64]: ot
Out[64]: '2013-10-10 23:40:00'



# 获取当前时间并转换为指定日期格式
import time

now = int(time.time())

timeArray = time.localtime(now)

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

In [70]: ot
Out[70]: '2018-05-05 15:57:17'



# 第二种方法
import datetime

now = datetime.datetime.now()

now.strftime("%Y-%m-%d %H:%M:%S")
Out[74]: '2018-05-05 15:58:56'



# 获得三天前的时间
import time,datetime

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

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

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

In [83]: timeStamp
Out[83]: 1525248061

In [84]: otherStyleTime
Out[84]: '2018-05-02 16:01:01'



# 给定日期字符串,直接转换为datetime对象
dateStr = '2013-10-10 23:40:00'

datetimeObj = datetime.datetime.strptime(dateStr, "%Y-%m-%d %H:%M:%S")

In [88]: datetimeObj
Out[88]: datetime.datetime(2013, 10, 10, 23, 40)



# 给定时间戳,计算该时间的几天前时间

timeStamp = 1381419600

import datetime,time

dateArray = datetime.datetime.utcfromtimestamp(timeStamp)

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

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


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

In [95]: timeStamp
Out[95]: 1381131600

In [96]: otherStyleTime
Out[96]: '2013-10-07 15:40:00'


# unix时间戳转日期

#1524734208为时间戳

time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1524734208))
 '2018-04-26 09:16:48'