我知道如何获取日期:
from datetime import datetime time = datetime.now() print(time)
但有没有办法可以计算出某个日期之前的日期/小时,也许可以将日期存储为整数或其他什么?感谢所有答案
只需创建另一个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