如何在datetime python模块中获取小时,分钟和秒的开始日期

时间:2014-12-21 22:37:02

标签: python datetime

我想了解日期的开始与该日期的任何其他时间之间的差异

例如

y = datetime.datetime(2012,1,1,1,1,1)

time_delta_in_seconds = (y.time()-datetime.time(0,0,0)).total_seconds()

但是我收到了以下错误

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time

有没有办法实现我的目标?

1 个答案:

答案 0 :(得分:3)

您可以使用combine方法构建一个新的日期时间,其小时,分钟,秒(和微秒)设置为0.两个日期时间的差异是timedelta,其中total_seconds方法

In [80]: import datetime as DT
In [81]: y = DT.datetime(2012,1,1,1,1,1)

In [82]: z = DT.datetime.combine(y, DT.time(0))
In [84]: z
Out[84]: datetime.datetime(2012, 1, 1, 0, 0)

In [83]: (y - z).total_seconds()
Out[83]: 3661.0