from datetime import datetime
local_time = datetime.now() #获取系统时间 local_time = datetime.datetime.now()
print type(local_time),"local_time= ",local_time
# 字符串转日期
data_time = datetime.strptime('2019-03-20 15:25:30', '%Y-%m-%d %H:%M:%S')
print type(data_time), data_time
Expenses_days = local_time–data_time
print Expenses_days
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> local_time = datetime.now() #获取系统时间 local_time = datetime.datetime.now()
>>> print type(local_time),"local_time= ",local_time
local_time= 2019-03-26 22:23:20.742000
>>> # 字符串转日期
... data_time = datetime.strptime('2019-03-20 15:25:30', '%Y-%m-%d %H:%M:%S')
>>> print type(data_time), data_time
2019-03-20 15:25:30
>>> Expenses_days = local_time-data_time
>>> print Expenses_days
6 days, 6:57:50.742000
>>> print Expenses_days.days
6
>>> print Expenses_days.seconds
25070
>>> print Expenses_days.microseconds
742000
>>> print Expenses_days.days+ Expenses_days.seconds/(24.0*60.0*60.0)
6.29016203704
print Expenses_days 显示 6 days, 6:57:50.742000
print Expenses_days.days 显示 6 天
print Expenses_days.seconds 显示 25070 秒 (25070/(60*60)) = 6.93小时,即6:57:50
print Expenses_days.microseconds 显示 742000 微妙
print Expenses_days.days+ Expenses_days.seconds/(24.0*60.0*60.0) 显示 6.29016203704天
所以当要计算2个精确的天数时间差的时候,需要用.days先算出整天,后用.seconds 算出秒数,再除以24*60*60(一天24小时,一小时60分,一分60秒),2者相加为精确的天数时间差。