gpt4 book ai didi

python - 在 Python 中对日期时间进行计算

转载 作者:行者123 更新时间:2023-11-28 21:21:55 25 4
gpt4 key购买 nike

我一直在尝试以下日期和时间操作:

import datetime
a = datetime.datetime.strptime("1899-12-30 19:45:00", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("1899-12-30 12:42:00", "%Y-%m-%d %H:%M:%S")
print (a-b)
print (a/b)

a-b 工作得很好,但 a/b 崩溃了:TypeError: unsupported operand type(s) for/: 'datetime.datetime' and 'datetime.datetime'

关于如何计算日期和时间值之间的关系有什么想法吗?我是否需要明确地首先计算每个变量 a 和 b 中的秒数,还是有更短的捷径?

如果我需要计算秒数。我该怎么做?我试过了

s = a.total_seconds()
which gives: AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

(我正在使用 Python 3.3)

最佳答案

你必须区分datetime.datetime (这是一个实际的日期和时间,例如“1899-12-30 19:45:00”)和 datetime.timedelta (这是一个句点,例如“1 小时”)。请注意,您的 a-b 减去两个日期时间将导致时间增量。

如果您要计算比赛时间,则必须指定比赛的开始时间(无论如何,您怎么知道比赛持续了多长时间)。然后你可以做

import datetime
start = datetime.datetime.strptime("1899-12-30 12:00:00", "%Y-%m-%d %H:%M:%S") # whatever the start time is
a = datetime.datetime.strptime("1899-12-30 19:45:00", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("1899-12-30 12:42:00", "%Y-%m-%d %H:%M:%S")
print (a-b) # it will give you the timedelta difference between racer "a" and racer "b"
print (a-start).total_seconds()/(b-start).total_seconds() # it will give you the ratio between "a" and "b" race times

没有为日期时间定义部门。但是 timedelta 对象有 total_seconds() 给你一个数字(以秒为单位的周期长度),你可以除以数字。


在 Python 3.x 中 print is a function因此需要括号,解决 AttributeError: 'NoneType' object has no attribute 'total_seconds':

print ((a-start).total_seconds()/(b-start).total_seconds())

关于python - 在 Python 中对日期时间进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20537803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com