如何在python中找到两个日期时间对象之间的时差?

时间:2009-08-28 09:03:15

标签: python datetime date-arithmetic

如何判断两个datetime个对象之间的时差(以分钟为单位)?

19 个答案:

答案 0 :(得分:286)

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 86400 + c.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

答案 1 :(得分:129)

Python 2.7的新功能是timedelta实例方法.total_seconds()。从Python文档中,这相当于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

参考:http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds

>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds

答案 2 :(得分:30)

使用日期时间示例

>>> from datetime import datetime
>>> then = datetime(2012, 3, 5, 23, 8, 15)        # Random date in the past
>>> now  = datetime.now()                         # Now
>>> duration = now - then                         # For build-in functions
>>> duration_in_s = duration.total_seconds()      # Total number of seconds between dates

持续时间

>>> years = divmod(duration_in_s, 31556926)[0]    # Seconds in a year=31556926.

持续时间

>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400

持续时间

>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600

持续时间(分钟)

>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60

持续时间(秒)

>>> seconds = duration.seconds                    # Build-in datetime function
>>> seconds = duration_in_s

持续时间(以微秒为单位)

>>> microseconds = duration.microseconds          # Build-in datetime function  

两个日期之间的总持续时间

>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))

或简单地说:

>>> print(now - then)

答案 3 :(得分:25)

从另一个中减去一个。你会得到一个与timedelta对象不同的对象。

>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)

您可以将dd.daysdd.secondsdd.microseconds转换为分钟。

答案 4 :(得分:19)

如果ab是日期时间对象,那么在Python 3中找到它们之间的时差:

from datetime import timedelta

time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)

在早期的Python版本中:

time_difference_in_minutes = time_difference.total_seconds() / 60

如果ab是天真的日期时间对象,例如由datetime.now()返回的,那么如果对象表示具有不同UTC偏移的本地时间,例如,在DST转换或附近,则结果可能是错误的过去/未来的日期。更多详情:Find if 24 hrs have passed between datetimes - Python

要获得可靠的结果,请使用UTC时间或时区感知的日期时间对象。

答案 5 :(得分:17)

使用divmod:

now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past

d = divmod(now-then,86400)  # days
h = divmod(d[1],3600)  # hours
m = divmod(h[1],60)  # minutes
s = m[1]  # seconds

print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)

答案 6 :(得分:7)

这是我获取两个datetime.datetime对象之间经过的小时数的方法:

before = datetime.datetime.now()
after  = datetime.datetime.now()
hours  = math.floor(((after - before).seconds) / 3600)

答案 7 :(得分:6)

只需查找天数:timedelta有一天的时间'属性。你可以简单地查询。

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

答案 8 :(得分:3)

只是认为在timedelta方面提及格式也许有用。 strptime()根据格式解析表示时间的字符串。

from datetime import datetime

datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'    
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'  
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)

这将输出:     0:05:00.518000

答案 9 :(得分:3)

这将给出以秒为单位的差异(然后除以 60 得到分钟):

import time
import datetime

t_start = datetime.datetime.now()

time.sleep(10)

t_end = datetime.datetime.now()
elapsedTime = (t_end - t_start )

print(elapsedTime.total_seconds())

输出:

10.009222

在我看来这是最简单的方法,您无需担心精度或溢出问题。

例如,使用 elapsedTime.seconds 会损失很多精度(它返回一个整数)。此外,正如 this answer 指出的那样,elapsedTime.microseconds 的上限为 10^6。因此,例如,对于 10 秒 sleep()elapsedTime.microseconds 给出 8325错误,应该大约为 10,000,000)。

答案 10 :(得分:2)

我使用这样的东西:

from datetime import datetime

def check_time_difference(t1: datetime, t2: datetime):
    t1_date = datetime(
        t1.year,
        t1.month,
        t1.day,
        t1.hour,
        t1.minute,
        t1.second)

    t2_date = datetime(
        t2.year,
        t2.month,
        t2.day,
        t2.hour,
        t2.minute,
        t2.second)

    t_elapsed = t1_date - t2_date

    return t_elapsed

# usage 
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)

print(elapsed_time)
#return : 0:08:52

答案 11 :(得分:1)

这是为了找出当前时间与9.30 am之间的时差

t=datetime.now()-datetime.now().replace(hour=9,minute=30)

答案 12 :(得分:1)

基于@Attaque great answer,我提出了日期时间差计算器的简化版:

seconds_mapping = {
    'y': 31536000,
    'm': 2628002.88, # this is approximate, 365 / 12; use with caution
    'w': 604800,
    'd': 86400,
    'h': 3600,
    'min': 60,
    's': 1,
    'mil': 0.001,
}

def get_duration(d1, d2, interval, with_reminder=False):
    if with_reminder:
        return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
    else:
        return (d2 - d1).total_seconds() / seconds_mapping[interval]

我已对其进行了更改,以避免声明重复功能,删除了漂亮的打印默认间隔,并增加了对毫秒,星期和ISO月份的支持(请注意,月份仅是近似值,基于每个月等于{{ 1}})。

哪个会产生:

365/12

答案 13 :(得分:1)

要获取struct Tree { Tree * left, * right; int element; }; //This function prints the given level of the given tree, assuming //that the node has the given x cordinate. void print_level(asciinode *node, int x, int level) { int i, isleft; if (node == NULL) return; isleft = (node->parent_dir == -1); if (level == 0) { for (i=0; i<(x-print_next-((node->lablen-isleft)/2)); i++) { printf(" "); } print_next += i; printf("%s", node->label); print_next += node->lablen; } else if (node->edge_length >= level) { if (node->left != NULL) { for (i=0; i<(x-print_next-(level)); i++) { printf(" "); } print_next += i; printf("/"); print_next++; } if (node->right != NULL) { for (i=0; i<(x-print_next+(level)); i++) { printf(" "); } print_next += i; printf("\\"); print_next++; } } else { print_level(node->left, x-node->edge_length-1, level-node->edge_length-1); print_level(node->right, x+node->edge_length+1, level-node->edge_length-1); } } //This function fills in the edge_length and //height fields of the specified tree void compute_edge_lengths(asciinode *node) { int h, hmin, i, delta; if (node == NULL) return; compute_edge_lengths(node->left); compute_edge_lengths(node->right); /* first fill in the edge_length of node */ if (node->right == NULL && node->left == NULL) { node->edge_length = 0; } else { if (node->left != NULL) { for (i=0; i<node->left->height && i < MAX_HEIGHT; i++) { rprofile[i] = -INFINITY; } compute_rprofile(node->left, 0, 0); hmin = node->left->height; } else { hmin = 0; } if (node->right != NULL) { for (i=0; i<node->right->height && i < MAX_HEIGHT; i++) { lprofile[i] = INFINITY; } compute_lprofile(node->right, 0, 0); hmin = MIN(node->right->height, hmin); } else { hmin = 0; } delta = 4; for (i=0; i<hmin; i++) { delta = MAX(delta, gap + 1 + rprofile[i] - lprofile[i]); } //If the node has two children of height 1, then we allow the //two leaves to be within 1, instead of 2 if (((node->left != NULL && node->left->height == 1) || (node->right != NULL && node->right->height == 1))&&delta>4) { delta--; } node->edge_length = ((delta+1)/2) - 1; } //now fill in the height of node h = 1; if (node->left != NULL) { h = MAX(node->left->height + node->edge_length + 1, h); } if (node->right != NULL) { h = MAX(node->right->height + node->edge_length + 1, h); } node->height = h; } asciinode * build_ascii_tree_recursive(Tree * t) { asciinode * node; if (t == NULL) return NULL; node = malloc(sizeof(asciinode)); node->left = build_ascii_tree_recursive(t->left); node->right = build_ascii_tree_recursive(t->right); if (node->left != NULL) { node->left->parent_dir = -1; } if (node->right != NULL) { node->right->parent_dir = 1; } sprintf(node->label, "%d", t->element); node->lablen = strlen(node->label); return node; } //Copy the tree into the ascii node structre asciinode * build_ascii_tree(Tree * t) { asciinode *node; if (t == NULL) return NULL; node = build_ascii_tree_recursive(t); node->parent_dir = 0; return node; } //Free all the nodes of the given tree void free_ascii_tree(asciinode *node) { if (node == NULL) return; free_ascii_tree(node->left); free_ascii_tree(node->right); free(node); } //The following function fills in the lprofile array for the given tree. //It assumes that the center of the label of the root of this tree //is located at a position (x,y). It assumes that the edge_length //fields have been computed for this tree. void compute_lprofile(asciinode *node, int x, int y) { int i, isleft; if (node == NULL) return; isleft = (node->parent_dir == -1); lprofile[y] = MIN(lprofile[y], x-((node->lablen-isleft)/2)); if (node->left != NULL) { for (i=1; i <= node->edge_length && y+i < MAX_HEIGHT; i++) { lprofile[y+i] = MIN(lprofile[y+i], x-i); } } compute_lprofile(node->left, x-node->edge_length-1, y+node->edge_length+1); compute_lprofile(node->right, x+node->edge_length+1, y+node->edge_length+1); } void compute_rprofile(asciinode *node, int x, int y) { int i, notleft; if (node == NULL) return; notleft = (node->parent_dir != -1); rprofile[y] = MAX(rprofile[y], x+((node->lablen-notleft)/2)); if (node->right != NULL) { for (i=1; i <= node->edge_length && y+i < MAX_HEIGHT; i++) { rprofile[y+i] = MAX(rprofile[y+i], x+i); } } compute_rprofile(node->left, x-node->edge_length-1, y+node->edge_length+1); compute_rprofile(node->right, x+node->edge_length+1, y+node->edge_length+1); } Here is the asciii tree structure… struct asciinode_struct { asciinode * left, * right; //length of the edge from this node to its children int edge_length; int height; int lablen; //-1=I am left, 0=I am root, 1=right int parent_dir; //max supported unit32 in dec, 10 digits max char label[11]; }; hourminute,您可以这样做

second

答案 14 :(得分:0)

这是我使用mktime的方法。

from datetime import datetime, timedelta
from time import mktime

yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()

difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60

答案 15 :(得分:0)

以其他方式区分日期;

import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

所以在Min。

获得输出

由于

答案 16 :(得分:0)

我使用时差进行连续集成测试,以检查和改进我的功能。如果有人需要,这是简单的代码

from datetime import datetime

class TimeLogger:
    time_cursor = None

    def pin_time(self):
        global time_cursor
        time_cursor = datetime.now()

    def log(self, text=None) -> float:
        global time_cursor

        if not time_cursor:
            time_cursor = datetime.now()

        now = datetime.now()
        t_delta = now - time_cursor

        seconds = t_delta.total_seconds()

        result = str(now) + ' tl -----------> %.5f' % seconds
        if text:
            result += "   " + text
        print(result)

        self.pin_time()

        return seconds


time_logger = TimeLogger()

使用:

from .tests_time_logger import time_logger
class Tests(TestCase):
    def test_workflow(self):
    time_logger.pin_time()

    ... my functions here ...

    time_logger.log()

    ... other function(s) ...

    time_logger.log(text='Tests finished')

在日志输出中我有类似的内容

2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished

答案 17 :(得分:0)

在不那么长的时间间隔内,您可能会发现此快速摘要很有用:

    from datetime import datetime as dttm
    time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
    delta = dttm.now() - time_ago
    days = delta.days # can be converted into years which complicates a bit…
    hours, minutes, seconds = map(int, delta.__format__('').split('.')[0].split(' ')[-1].split(':'))

在Python v.3.8.6上进行了测试

答案 18 :(得分:-1)

import datetime
date = datetime.date(1, 1, 1)
#combine a dummy date to the time
datetime1 = datetime.datetime.combine(date, start_time)
datetime2 = datetime.datetime.combine(date, stop_time)  
#compute the difference
time_elapsed = datetime1 - datetime2

start_time --> 日期时间对象的开始时间
end_time--> datetime 对象的结束时间

我们不能直接减去 datetime.time 对象
因此我们需要为其添加一个随机日期(我们使用组合)
或者您可以使用“今天”代替 (1,1,1)

希望能帮到你