英文:
how do I calculate the average of two datetime objects
问题
我有一个包含日期时间对象的列表,并且想要在列表中满足特定条件时计算两个时间的平均值,并将其插入列表中。
temp = datetime.fromtimestamp(offsetMat[i][j].timestamp() + offsetMat[i][j+1].timestamp() / 2)
offsetMat[i].insert(j, temp)
我尝试了这段代码,但从计算得到的结果来看似乎不合理。
英文:
I have a list containing datetime objects and want to calculate the average of two times from the list when a certain condition is met and insert it into the list.
temp =datetime.fromtimestamp(offsetMat[i][j].timestamp()+offsetMat[i][j+1].timestamp()/2)
offsetMat[i].insert(j,temp)
I tried this code but the result i get from the calculation doesn't make sense.
答案1
得分: 1
from datetime import datetime
Example datetime objects
dt1 = datetime(2023, 5, 1, 12, 0, 0)
dt2 = datetime(2023, 5, 3, 12, 0, 0)
Calculate the average datetime
total_seconds = (dt2 - dt1).total_seconds()
average_seconds = total_seconds / 2
average_datetime = datetime.fromtimestamp(dt1.timestamp() + average_seconds)
Print the result
print(average_datetime)
英文:
Tty this and check if it works:
from datetime import datetime
# Example datetime objects
dt1 = datetime(2023, 5, 1, 12, 0, 0)
dt2 = datetime(2023, 5, 3, 12, 0, 0)
# Calculate the average datetime
total_seconds = (dt2 - dt1).total_seconds()
average_seconds = total_seconds / 2
average_datetime = datetime.fromtimestamp(dt1.timestamp() + average_seconds)
# Print the result
print(average_datetime)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论