计算日期时差python [英] Calculate date time difference python

查看:86
本文介绍了计算日期时差python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写timediff函数以计算2个给定日期时间之间的时间(秒)差异

I am writing timediff function to calculate the time (seconds) difference between 2 giving date time

def timediff(time1, time2):
    timeformat = '%d%b%Y:%H:%M:%S'
    #time1="01MAR2016:07:11:53"
    #time2="01MAR2016:16:28:38"

    try:
        date_object1 = datetime.strptime(time1, timeformat)
        date_object2 = datetime.strptime(time2, timeformat)
    except ValueError:
        print "time1 format: " + repr(time1)
        print "time2 format: " + repr(time2)
        raise                      

    return abs((date_object2 - date_object1).seconds)  

似乎不带月,日,年计算。如果它在相同的月,日,年中,则给出正确的计算。

It seems to not take the "month, date, year" to the calculation. It gives the right calculation if it is in the same "month, date, year"

>>> t1="01MAR2016:07:11:53"
>>> t2="01MAR2016:16:28:38"
>>> timediff(t1, t2)
33405

但是具有不同的月,日,年 ,它给出了错误的答案。这只会计算约18小时的时间差(约65k秒)

However with different "month, date, year", it gives the wrong answer. This only calculates time difference ~18hrs (which gives ~65k seconds)

>>> t1="02APR2016:06:43:51"
>>> t2="06APR2016:00:58:03"
>>> timediff(t1, t2)
65652

或者24小时不同,它给出0

Or 24hrs different it gives 0

>>> t1="01MAR2016:07:11:53"
>>> t2="02MAR2016:07:11:53"
>>> timediff(t1, t2)
0

datetime采用我给出的时间格式

The datetime takes the time format I gives

>>> t1="01MAR2016:07:11:53"
>>> t2="02MAR2016:07:11:53"
>>> datetime.strptime(t1, timeformat)
datetime.datetime(2016, 3, 1, 7, 11, 53)
>>> datetime.strptime(t2, timeformat)
datetime.datetime(2016, 3, 2, 7, 11, 53)

我错过了什么吗?

我还有另一种将日期时间转换为秒的方法。但是仍然想知道为什么这种方法行不通。

I have another alternative which convert date time to seconds. But still want to know why this method doesnt work.

我的选择

def timediff(time1, time2):
    timeformat = '%d%b%Y:%H:%M:%S'
    t1 = datetime.strptime(time1, timeformat)
    t2 = datetime.strptime(time2, timeformat)

    return abs(time.mktime(t1.timetuple()) - time.mktime(t2.timetuple()))

示例:

>>> t2
'02MAR2016:07:11:53'
>>> t1
'01MAR2016:07:11:53'
>>> timediff(t1,t2)
86400.0


推荐答案

您需要使用 total_seconds()而不是 seconds

>>> import datetime
>>> f = '%d%b%Y:%H:%M:%S'
>>> t1 = '01MAR2016:07:11:53'
>>> t2 = '02MAR2016:07:11:53'
>>> d1 = datetime.datetime.strptime(t1, f)
>>> d2 = datetime.datetime.strptime(t2, f)
>>> print(d2-d1)
1 day, 0:00:00
>>> print((d2-d1).total_seconds())
86400.0
>>> print((d2-d1).seconds)
0

这篇关于计算日期时差python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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