I know how to get the date:
from datetime import datetime
time = datetime.now()
print(time)
But is there a way where you can work out the days/hours until a certain date, maybe storing the date as an integer or something? Thx for all answers
datetime in Python is the combination between dates and times. The attributes of this class are similar to both date and separate classes. These attributes include day, month, year, minute, second, microsecond, hour, and tzinfo.
Python datetime Classesdatetime – Allows us to manipulate times and dates together (month, day, year, hour, second, microsecond). date – Allows us to manipulate dates independent of time (month, day, year).
Just create another datetime object and subtract which will give you a timedelta object.
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
If you want to take user input:
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)
Demo:
$Enter date in format yyyy/mm/dd hh:mm:ss2016/01/01 00:00:00
15 days, 3:04:51.960110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With