python中日期类datetime功能比较强大,使用起来很方便,把常用的两种用法总结如下:
from datetime import datetime
from datetime import timedelta
# 日期格式转换为字符串
NOW = datetime.now()
TODAY = NOW.strftime("%Y%m%d")
YESTERDAY = (NOW -timedelta(days=1)).strftime("%Y%m%d")
# 字符串转换为日期
d1 = str(20180301)
d2 = str(20180226)
print type(d1)
d1 = datetime.strptime(d1, '%Y%m%d')
d2 = datetime.strptime(d2, '%Y%m%d')
# 计算 d1与d2之间的差值
print (d1 - d2).days