python 蟒蛇时间操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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'
以上是关于python 蟒蛇时间操作的主要内容,如果未能解决你的问题,请参考以下文章
python 蟒蛇文件操作
python 蟒蛇操作数据库
python 蟒蛇操作的Redis
python 蟒蛇日期操作
python 蟒蛇操作的MySQL数据库
python 如何在Python中中断长时间运行的操作。 #蟒蛇