python 时间戳、datetime、字符串的相互转换

# -*- coding: utf-8 -*-
import time
import datetime
#当前时间datetime
now = datetime.datetime.now()
print('\n当前时间datetime:\t%s,类型:%s'%(now,type(now)))
#当前时间str
now_str = str(now)
print('当前时间str:\t\t%s,类型:%s'%(now_str,type(now_str)))
#当前时间时间戳
now_mktime =time.time()
print('当前时间时间戳:\t%s,类型:%s'%(now_mktime,type(now_mktime)))
#今天、昨天、明天
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tommorrow = today + datetime.timedelta(days=1)
print('\n今天:%s,昨天:%s,明天:%s'%(today,yesterday,tomorrow))
#任意时间字符串转为datetime
today_8 = str(today)[0:10]+' 08:00:00'
today_8_time = datetime.datetime.strptime(today_8,'%Y-%m-%d %H:%M:%S')
print('获取当天任意时间:',today_8,'类型:',type(today_8),today_8_time,'类型:',type(today_8_time))
#datetime转为字符串
now_str = datetime.datetime.strftime(now,'%Y-%m-%d %H:%M:%S')
now_str_1 = str(now)[0:19]
print('\ndatetime转为字符串:\t%s,类型:%s'%(now_str,type(now_str)))
#字符串转为datetime
str2datetime = datetime.datetime.strptime(now_str,'%Y-%m-%d %H:%M:%S')
now_time_1 = datetime.datetime.strptime(str(now)[0:19],'%Y-%m-%d %H:%M:%S')
print('字符串转为datetime:\t%s,类型:%s'%(str2datetime,type(str2datetime)))
#将datetime转为时间戳
datetime2mktime = time.mktime(today.timetuple())
print('\ndatetime转为时间戳:\t%s,类型:%s'%(datetime2mktime,type(datetime2mktime)))
#将时间戳转为datetime
mktime2datetime = datetime.datetime.fromtimestamp(now_mktime)
print('时间戳转为字符串:\t%s,类型:%s'%(mktime2datetime,type(mktime2datetime)))
#字符串转为时间戳
str2mktime = time.mktime(time.strptime(str(today), '%Y-%m-%d'))
print('\n字符串转为时间戳:\t%s,类型:%s'%(str2mktime,type(str2mktime)))
#时间戳转为字符串
# time.localtime()将时间戳转换为struct_time
mktime2str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_mktime))
print('时间戳转为字符串:\t%s,类型:%s'%(mktime2str,type(mktime2str)))

输出结果:

当前时间datetime: 2019-08-04 18:48:10.211342,类型:<class 'datetime.datetime'>
当前时间str: 2019-08-04 18:48:10.211342,类型:<class 'str'>
当前时间时间戳: 1564915690.2113426,类型:<class 'float'>

今天:2019-08-04,昨天:2019-08-03,明天:2019-08-05
获取当天任意时间: 2019-08-04 08:00:00 类型: <class 'str'> 2019-08-04 08:00:00 类型: <class 'datetime.datetime'>

datetime转为字符串: 2019-08-04 18:48:10,类型:<class 'str'>