Python 计算多少天前后、距离X日多久的日期-Python 实用宝典

# Python 计算多少天前后、距离X日多久的日期

```# 文件名：count_days.py
import time
import datetime

def get_between_days(start_date, end_date):
# 获得两个日期之间的天数
start_sec = time.mktime(time.strptime(start_date,'%Y-%m-%d'))
end_sec = time.mktime(time.strptime(end_date,'%Y-%m-%d'))
work_days = int((end_sec - start_sec)/(24*60*60))
work_hours = int((end_sec - start_sec)/(60*60))
work_minutes = int((end_sec - start_sec)/(60))
return work_days, work_hours, work_minutes
# 获得当天时间 yyyy-mm-dd
start_date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
end_date = '2019-09-01'
print (get_between_days(start_date, end_date))```

`time.mktime(time.strptime(start_date,'%Y-%m-%d'))`

strptime是将yyyy-mm-dd这样的字符串转化为time类型的变量，然后time.mktime()函数可以将time类型的变量转化为时间戳。

`work_days = int((end_sec - start_sec)/(24*60*60))`

`work_hours = int((end_sec - start_sec)/(60*60))`

`work_minutes = int((end_sec - start_sec)/(60))`

python count_days.py

```# 文件名：count_days.py
import time
import datetime
def time_controller(d=0, hour=0, minute=0, second=0, arg=1, day=datetime.datetime.now()):
# 获得某天的x天、y小时、t分钟、z秒后的日期, day为空默认为当前时间开始
# 所有参数默认都为0，只需要调你需要的时间即可
# arg = 1: 获得hour小时,minute分钟,second秒后的具体时间
# arg = -1: 获得hour小时,minute分钟,second秒前的具体时间
now = datetime.datetime.now()
if type(day) == str:
now = datetime.datetime.strptime(day, '%Y-%m-%d %H:%M:%S')
if arg == 1:
value = now + datetime.timedelta(days=d, hours=hour, minutes=minute, seconds=second)
elif arg == -1:
value = now - datetime.timedelta(days=d, hours=hour, minutes=minute, seconds=second)
return value
print(time_controller(d=10, hour=20, minute=10, second=0, arg=-1, day='2019-08-01 10:00:00'))
print(time_controller(d=10, hour=20, minute=10, second=0, arg=-1))```

python count_days.py