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

Ent*_*ast 2 python datetime python-3.x

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

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)
Run Code Online (Sandbox Code Playgroud)

ab可以超级运行,但a / b会崩溃:TypeError:/的不受支持的操作数类型:“ datetime.datetime”和“ datetime.datetime”

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

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

s = a.total_seconds()
which gives: AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'
Run Code Online (Sandbox Code Playgroud)

(我正在使用Python 3.3)

lee*_*dam 5

您必须在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
Run Code Online (Sandbox Code Playgroud)

没有为日期时间定义除法。但是timedelta对象具有total_seconds()给您一个数字(以秒为单位的时间长度),并且您可以将数字相除。


在Python 3.x中,print是一个函数,因此需要括号,以解决以下问题AttributeError: 'NoneType' object has no attribute 'total_seconds'

print ((a-start).total_seconds()/(b-start).total_seconds())
Run Code Online (Sandbox Code Playgroud)