Datetime相减计算总秒数遇到的坑

一直以为Python里两个datetime类型相减然后获取seconds拿到的是两个时间相差的总秒数,其实并不是。。。

正确的获取方法应该是用total_seconds()

示例:

1
2
3
4
first_time = datetime.datetime(2013,11,10,11,11,11)
last_time = datetime.datetime(2014,11,10,11,11,11)
delta = last_time - first_time
print delta.total_seconds()

timedelta 相关的文档中这样写到:

1
2
3
4
5
6
7
8
9
10
11
12
Only days, seconds and microseconds are stored internally. Arguments are converted to those units:
A millisecond is converted to 1000 microseconds.
A minute is converted to 60 seconds.
An hour is converted to 3600 seconds.
A week is converted to 7 days.
and days, seconds and microseconds are then normalized so that the representation is unique, with
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999

在Python2.7中加入了timedelta.total_seconds()方法:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days 24 3600) 10*6) / 106 computed with true division enabled.

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

timedelta官方示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
... minutes=50, seconds=600) # adds up to 365 days
>>> year.total_seconds()
31536000.0
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3;
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True