“专业人士笔记”系列目录:
创帆云:Python成为专业人士笔记--强烈建议收藏!每日持续更新!zhuanlan.zhihu.com两个 date-times之间的时间间隔
from datetime import datetime
a = datetime(2016,10,6,0,0,0)
b = datetime(2016,10,1,23,59,59)
a-b
#输出对象:datetime.timedelta,值为4 days, 0:00:01
(a-b).days
#输出间隔天数: 4
(a-b).total_seconds()
#输出间隔秒数 : 345601.0
datetime对象转化成字符串
from datetime import datetime
datetime_for_string = datetime(2016,10,1,0,0)
datetime_string_format = '%b %d %Y, %H:%M:%S'#设置转成string的对应解析格式
print(datetime.strftime(datetime_for_string,datetime_string_format))
#使用strftime函数,完成datatime到字符串之间的转换
#输出Oct 01 2016, 00:00:00
将字符串转换为datetime对象
from datetime import datetime
datetime_string = 'Oct 1 2016, 00:00:00'
datetime_string_format = '%b %d %Y, %H:%M:%S' #设定解析格式
datetime.strptime(datetime_string, datetime_string_format)
#使用strptime函数,完成由字符串至Datatime之间的互转
#输出对象:datetime.datetime:(2016, 10, 1, 0, 0)