这是一些原型代码,给定两个日期将打印它们之间的时间:
from datetime import datetime
date_format= "%m/%d/%y"
now=datetime.now()
print now
d1=datetime.now()
d2=datetime.strptime('07/21/14',date_format)
delta= d2-d1
print delta
我想修改它,以便它向用户询问两个日期,而不是在源代码中硬编码日期。
到目前为止,我已写过:
date1=raw_input("What is date 1 ?:")
print date1
date2=raw_input("What is date 2 ?:")
print date2
delta=date2-date1
print delta
但在输入我的日期后,我收到错误:
Traceback (most recent call last):
File "C:/Python27/datetimetest.py", line 17, in <module>
delta=date2-date1
TypeError: unsupported operand type(s) for -: 'str' and 'str'
答案 0 :(得分:1)
您需要将从raw_input()
获得的字符串转换为日期对象。就像你在原始代码中所做的一样。
from datetime import datetime
date_format= "%m/%d/%y"
date1 = raw_input("What is date 1: ")
date1 = datetime.strptime(date1, date_format)
date2 = raw_input("What is date 2: ")
date2 = datetime.strptime(date2, date_format)
print
print 'Date 1:', date1
print 'Date 2:', date2
print 'Delta: ', date2 - date1
如果我们运行这个:
What is date 1: 3/14/12
What is date 2: 3/16/12
Date 1: 2012-03-14 00:00:00
Date 2: 2012-03-16 00:00:00
Delta: 2 days, 0:00:00