我知道如何获取日期:
from datetime import datetime
time = datetime.now()
print(time)
但是有没有办法可以计算出某个日期之前的日/小时,也许可以将日期存储为整数或其他东西?所有答案的答案
答案 0 :(得分:7)
只需创建另一个datetime对象并减去哪个会给你一个timedelta对象。
from datetime import datetime
now = datetime.now()
then = datetime(2016,1,1,0,0,0)
diff = then - now
print(diff)
print(diff.total_seconds())
15 days, 3:42:21.408581
1309365.968044
如果您想接受用户输入:
from datetime import datetime
while True:
inp = input("Enter date in format yyyy/mm/dd hh:mm:ss")
try:
then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S")
break
except ValueError:
print("Invalid input")
now = datetime.now()
diff = then - now
print(diff)
演示:
$Enter date in format yyyy/mm/dd hh:mm:ss2016/01/01 00:00:00
15 days, 3:04:51.960110
答案 1 :(得分:0)
我已经回答并开发了它,以便用户可以输入他们想要的日期:这里是
from datetime import datetime
year=int(input("What year?"))
month=int(input("What month?"))
day=int(input("What day?"))
hour=int(input("What hour?"))
minute=int(input("What minute?"))
second=int(input("What second?"))
then = datetime(year,month,day,hour,minute,second)
now = datetime.now()
diff = then - now
print(diff)
print(diff.total_seconds())
谢谢大家的答案:D
现在变量
这里有更好的代码,你可以取出now变量,直接把它放在差值整数
from datetime import datetime
while True:
inp = input("Enter date in format yyyy/mm/dd hh:mm:ss")
try:
then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S")
break
except ValueError:
print("Invalid input")
diff = then - datetime.now()
print(diff, "until", inp)
print(diff.total_seconds(),"seconds")