Subtracting asctime from time module to get hours minutes and seconds in python.

huangapple go评论57阅读模式
英文:

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

&lt; some code here&gt;

end = time.asctime(time.localtime(time.time()))

print(end - start)

答案1

得分: 1

您可以使用Python中的datetime模块来减去两个datetime对象,从而获得一个表示两个时间之间持续时间的timedelta对象。timedelta对象可以通过访问其属性total_seconds()secondsminuteshoursdays来进一步提取小时、分钟和秒。以下是一个示例:

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)

huangapple
  • 本文由 发表于 2023年2月7日 00:35:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定