timestring='2018-06-26 10:14:49'
# 字符串时间转为时间戳
def Changetime(str1):
Unixtime = int(time.mktime(time.strptime(str1, '%Y-%m-%d %H:%M:%S'))*1000)
return Unixtime
t1 = time.strptime(str1, '%Y-%m-%d %H:%M:%S') #将字符串转存成时间元组
t2 = Changetime(timestring) #1529979289000
time.localtime([timestamp]):将时间戳转会为时间元组
timestamp = time.time() #1530098655.6190026
timestruct = time.localtime(timestamp)
t3 = time.strftime('%Y-%m-%d %H:%M:%S', timestruct) #'2018-06-27 19:24:15'
import datetime
timestamp = 1530098655.6190026
datetime_struct = datetime.datetime.fromtimestamp(timestamp)
t4 = datetime_struct.strftime('%Y-%m-%d %H:%M:%S') #'2018-06-27 19:24:15'
datetime_struct = datetime.datetime.utcfromtimestamp(timestamp)
t5 = datetime_struct.strftime('%Y-%m-%d %H:%M:%S') #'2018-06-27 11:24:15'
#几天/周前
import datetime
import time
now = datetime.datetime.now()
three_days_ago = now + datetime.timedelta(days=-3)
three_weeks_ago = now + datetime.timedelta(weeks=-3)
#几天/周后
three_days_later = now + datetime.timedelta(days=3)
three_weeks_later = now + datetime.timedelta(weeks=3)
#获取时间差
start = datetime.datetime.now()
time.sleep(30)
end = datetime.datetime.now()
print (end-start).days # 0 天数
print (end-start).total_seconds() # 30.029522 精确秒数
print (end-start).seconds # 30 秒数
print (end-start).microseconds # 29522 毫秒数
dateutil 与日期相关库里的一个日期解析器 能够将字符串 转换为日期格式
import time
from dateutil import parser
time_string = time.ctime() # 'Wed Jun 27 19:40:17 2018' 可以是任意的时间格式 <type str>
datetime_struct = parser.parse(time_string)
print type(datetime_struct) # <type 'datetime.datetime'>
print datetime_struct.strftime('%Y-%m-%d %H:%M:%S') # 2018-06-27 19:40:17
时间戳参考文献
python 第三方库 dateutil.parser 使用说明