将datetime转换为timedelta,以便添加它们

时间:2015-03-23 22:05:20

标签: python datetime timedelta

当减去两个datetime个对象时,我理解结果是timedelta对象:

import datetime

AcDepart = 1900-01-01 18:00:00
AcArrival = 1900-01-01 07:00:00
ActualHours = AcDepart - AcArrival 

我想从date time

中减去另外两个ActualHours个对象的总和

这是另外两个对象:

HrsEarly = 1900-01-01 02:00:00
HrsLate = 1900-01-01 00:30:00

这是无法完成的等式:

UnCalcTime = ActualHours - (HrsEarly + HrsLate)

这是错误:

UnCalcTime = ActualHours - (HrsEarly + HrsLate)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'

所以,我显然无法添加datetime.datetime。有谁知道我怎么能解决这个问题?可以timedelta加在一起吗?如果是,我该如何将datetime转换为timedelta

任何帮助都会非常感激,因为我一直试图解决这个问题很长时间没有成功。

3 个答案:

答案 0 :(得分:3)

最佳解决方案是首先将变量创建为timedelta

HrsEarly = datetime.timedelta(hours=2)
HrsLate = datetime.timedelta(minutes=30)

如果你不能这样做,你可以简单地从datetime对象中减去“零日期”。

>>> HrsEarly
datetime.datetime(1900, 1, 1, 2, 0)
>>> HrsEarly = HrsEarly - datetime.datetime(1900, 1, 1)
>>> HrsEarly
datetime.timedelta(0, 7200)

答案 1 :(得分:2)

将字符串转换为timedelta

from datetime import datetime

AcDepart = '1900-01-01 18:00:00'
AcDepart_ = datetime.strptime(AcDepart, '%Y-%m-%d %H:%M:%S')
AcArrival = '1900-01-01 07:00:00'
AcArrival_ = datetime.strptime(AcArrival, '%Y-%m-%d %H:%M:%S')
ActualHours = (AcDepart_ - AcArrival_).total_seconds()/3600
print ActualHours

答案 2 :(得分:0)

创建一个 modules.py 并粘贴以下两个函数。将它们导入到您想要的任何位置并按原样使用。

import datetime

def JsTimestampToPyDatetime(js_date):
    """
        converts javascript timestamp to python datetime taking care of 
        milliseconds and seconds

        Args:
            js_date(Timestamp, required)

        Returns:
            Datetime
    """

    try:
        # handles seconds
        date = datetime.datetime.fromtimestamp(int(js_date))
    except (ValueError):
        # handles miliseconds
        date = datetime.datetime.fromtimestamp(int(js_date) / 1000)
       
    return date

# consuming javascript generated timestamps

a = JsTimestampToPyDatetime(1627303810000) # with miliseconds
b = JsTimestampToPyDatetime(1627476610) # with seconds only


def GetDaysInDateTime(min_stamp, max_stamp):
    """
        Calculates time difference between two timestamps in days

        Args:
            min_stamp(Datetime, required): Minimum/start datetime
            max_stamp(Datetime, required): Maximum/end datetime

        Returns:
            Int: Days
    """

    days = (max_stamp-min_stamp).days
    return int(days)


print(GetDaysInDateTime(a, b))