python timedelta减法行为 [英] python timedelta behaviour on subtraction

查看:50
本文介绍了python timedelta减法行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题起源于我遇到的问题(解决方案

timedelta 并不代表从午夜开始的时间,仅代表时间量./p>

如果我花了三个小时减去四个小时来完成某件事,那么我将需要负一小时.

两个 timedelta 之间的差是负一天 45分钟.

这与负23小时15分钟相同.

15分钟减去 23小时30分钟负23小时15分钟.

This question originated when I came upon (another thread) about python's datetime and timedelta instances

I followed the update by jimgardener and read the comments by eyquem ,and tried out some python code ..I am having a bad time understanding the way things work here(due to my newbie to python status)..I thought it was proper to ask a new question

import datetime
#for t1=23:30:00 PM
t1 = datetime.time(23,30,00)

#for t1=00:15:30 AM
t2 = datetime.time(0,15,30)

td1 = datetime.timedelta(hours=t1.hour,minutes = t1.minute,seconds=t1.second)

td2 = datetime.timedelta(hours=t2.hour,minutes = t2.minute,seconds=t2.second)

#substarcting timedeltas
tdiff = td2-td1

printing these variables yielded

td1 ==> datetime.timedelta(0, 84600)
td1.seconds ==> 84600

td2 ==> datetime.timedelta(0, 930)
td2.seconds ==> 930

tdiff ==> datetime.timedelta(-1, 2730)

When I looked at these results,I noticed that

td1.seconds (ie 84600) is equivalent to 
84600/60 ==> 1410 minutes
1410/60 ==> 23.5 hours
or in short,td1 represents the duration **from previous midnight** to 23:30 PM

now ,

td2.seconds (ie 930) is equivalent to
930/60 ==> 15.5 minutes or 15 minutes and 30 seconds
which means td2 represents the duration from **that midnight**
 to 00:15:30 AM

when tdiff is examined,I found that

tdiff ==> timedelta(-1,2730)
tdiff.seconds ==> 2730
tdiff.seconds/60 ==>45 minutes

this is the same as duration between t1(23:30:00 PM) and t2(00:15:30 AM) assuming that t2 follows t1

My question is,since td1 is the duration from previous midnight to 23:30:00 PM and td2 is the duration from that midnight to 00:15:30 AM , how can their difference represent the duration between t2 and t1 ?

Can some python gurus explain

解决方案

The timedeltas don't represent time from a midnight, just an amount of time.

If it took me three hours minus four hours to do something, it would take me negative one hour.

The difference between the two timedeltas is negative one day plus 45 minutes.

This is the same as negative 23 hours and 15 minutes.

15 minutes minus 23 hours and 30 minutes is negative 23 hours and 15 minutes.

这篇关于python timedelta减法行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆