Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you do sums with a datetime in Python?

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

like image 324
Beastly Gerbil Avatar asked Dec 16 '15 20:12

Beastly Gerbil


People also ask

What is datetime used for in Python?

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.

What is difference between datetime and date Python?

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).


1 Answers

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
like image 140
Padraic Cunningham Avatar answered Oct 14 '22 00:10

Padraic Cunningham