计算两个日期时间对象的平均值。

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

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)

huangapple
  • 本文由 发表于 2023年5月6日 16:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187944.html
匿名

发表评论

匿名网友

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

确定