你能用Python中的日期时间总结吗?

Bea*_*bil 6 python python-3.x

我知道如何获取日期:

from datetime import datetime
time = datetime.now()
print(time)
Run Code Online (Sandbox Code Playgroud)

但有没有办法可以计算出某个日期之前的日期/小时,也许可以将日期存储为整数或其他什么?感谢所有答案

Pad*_*ham 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
Run Code Online (Sandbox Code Playgroud)

如果您想获取用户输入:

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)
Run Code Online (Sandbox Code Playgroud)

演示:

$Enter date in format yyyy/mm/dd hh:mm:ss2016/01/01 00:00:00
15 days, 3:04:51.960110
Run Code Online (Sandbox Code Playgroud)


Bea*_*bil 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())
Run Code Online (Sandbox Code Playgroud)

谢谢大家的回答: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")
Run Code Online (Sandbox Code Playgroud)