Convert timedelta to total seconds
我有时差
1 2 3 4 | time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) ... time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) diff = time2 - time1 |
现在,我如何找到通过的总秒数?
1 | diff.seconds + diff.days * 24 * 3600 |
有没有内置的方法?
使用
1 2 3 | >>> import datetime >>> datetime.timedelta(seconds=24*60*60).total_seconds() 86400.0 |
您的
(1)如果您需要的只是两个瞬间的差异,那么非常简单的
(2)如果你将这些时间戳用于其他目的,你需要考虑你在做什么,因为结果有很大的气味:
我在澳大利亚墨尔本,标准TZ是UTC + 10,但夏令时仍然有效,直到明天早上,所以它是UTC + 11。当我执行以下操作时,它是2011-04-02T20:31当地时间...... UTC是2011-04-02T09:31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | >>> import time, datetime >>> t1 = time.gmtime() >>> t2 = time.mktime(t1) >>> t3 = datetime.datetime.fromtimestamp(t2) >>> print t0 1301735358.78 >>> print t1 time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC >>> print t2 1301700663.0 >>> print t3 2011-04-02 10:31:03 ### this is UTC+1 >>> tt = time.time(); print tt 1301736663.88 >>> print datetime.datetime.now() 2011-04-02 20:31:03.882000 ### UTC+11, my local time >>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt) 2011-04-02 09:31:03.880000 ### UTC >>> print time.localtime() time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time |
您会注意到t3,您的表达式的结果是UTC + 1,它似乎是UTC +(我的本地DST差异)......不是很有意义。您应该考虑使用
您可以使用mx.DateTime模块
1 2 3 4 5 | import mx.DateTime as mt t1 = mt.now() t2 = mt.now() print int((t2-t1).seconds) |