英文:
Subtracting asctime from time module to get hours minutes and seconds in python
问题
You can subtract start
from end
to calculate the time difference in Python. Here's the code with the print statement converted as you requested:
import time
start = time.asctime(time.localtime(time.time()))
# < some code here >
end = time.asctime(time.localtime(time.time()))
time_format = "%a %b %d %H:%M:%S %Y"
start_time = time.mktime(time.strptime(start, time_format))
end_time = time.mktime(time.strptime(end, time_format))
time_difference = end_time - start_time
hours, remainder = divmod(time_difference, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
This code will calculate and print the time difference in hours, minutes, and seconds between end
and start
.
英文:
How can I subtract end - start to get hours minutes and seconds of time completion in Python?
I have some pseudocode here, I want to convert the print statement to what I said above.
start = time.asctime(time.localtime(time.time()))
< some code here>
end = time.asctime(time.localtime(time.time()))
print(end - start)
答案1
得分: 1
您可以使用Python中的datetime
模块来减去两个datetime
对象,从而获得一个表示两个时间之间持续时间的timedelta
对象。timedelta
对象可以通过访问其属性total_seconds()
、seconds
、minutes
、hours
和days
来进一步提取小时、分钟和秒。以下是一个示例:
import datetime
start = datetime.datetime.now()
end = datetime.datetime.now()
duration = end - start
hours, remainder = divmod(duration.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
英文:
a solution using datetime
You can use the datetime
module in Python to subtract two datetime
objects and obtain a timedelta
object that represents the duration between the two times. The timedelta
object can be further used to extract hours, minutes, and seconds by accessing its attributes total_seconds()
, seconds
, minutes
, hours
, and days
. Here is an example:
import datetime
start = datetime.datetime.now()
end = datetime.datetime.now()
duration = end - start
hours, remainder = divmod(duration.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论