我需要通过获取日期作为用户输入来查找两个日期之间的天数差异。我尝试使用获取日期raw_input
但我收到错误。我正在使用 2.7 版本的 python。
import time
from datetime import date
day1 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
diff = day2-day1
print diff
您需要将这些日期解析为更有意义的内容。使用datetime.datetime.strptime() http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime method:
from datetime import datetime
day1 = raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = raw_input("enter the date in this format (yyyy:mm:dd)")
day1 = datetime.strptime(day1, '%Y:%m:%d').date()
day2 = datetime.strptime(day2, '%Y:%m:%d').date()
diff = day2 - day1
print diff.days
The datetime.datetime.date()
方法仅返回结果的日期部分datetime
object.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)