Hopefully just a simple question. I want to convert a datetime object to seconds and include the days. I've just noticed that my code skipped the day. Please note times are just an example and not 100% accurate.
Content of oldtime.txt (2 days ago):
2021-09-16 19:34:33.569827
Code:
oldtimefile = open('oldtime.txt', 'r ')
oldtme = oldtimefile.read()
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.seconds)
If I just print finaltime
then I get 1 day, 22:13:30.231916
.
Now if we take today's date and time - just for argument sake - (2021-09-18 17:34:33.569827
) as now
then I actually get 80010
seconds instead of roughly 172800
seconds. It's ignoring the day part.
How can I include the day and convert the entire object to seconds?
Thanks.
CodePudding user response:
Instead of .seconds
you can use .total_seconds()
:
from datetime import datetime
oldtme = "2021-09-16 19:34:33.569827"
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.total_seconds())
Prints:
164254.768354