如何在python中减去日期时间/时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31929538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:45:38  来源:igfitidea点击:

How to subtract datetimes / timestamps in python

pythondatetime

提问by Jeff F

Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:

看起来这应该很简单,但对于我的生活,我找不到答案。我从数据库中提取两个日期时间/时间戳:

2015-08-10 19:33:27.653
2015-08-10 19:31:28.209

How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.

如何从第二个中减去第一个,最好以毫秒为单位的结果?是的,我也有日期,因为我也需要它在午夜左右工作。

采纳答案by Yaroslav Admin

Parse your strings as datetime.datetimeobjects and subtract them:

将您的字符串解析为datetime.datetime对象并减去它们:

from datetime import datetime

d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")

print(d1 - d2)

Gives me:

给我:

0:01:59.444000

Also check out timedeltadocumentation for all possible operations.

还要查看timedelta所有可能操作的文档。

回答by Chris Montanaro

you can do subtraction on 2 datetime objects to get the difference

您可以对 2 个日期时间对象进行减法运算以获得差异

>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10

convert your strings to datetime objects with time.strptime

使用time.strptime将字符串转换为日期时间对象

datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")

回答by cameron-f

For python 3.4, first you'd need to convert the strings representing times into datetime objects, then the datetimemodule has helpful tools work with dates and times.

对于python 3.4,首先您需要将表示时间的字符串转换为日期时间对象,然后日期时间模块具有处理日期和时间的有用工具。

from datetime import datetime

def to_datetime_object(date_string, date_format):
    s = datetime.strptime(date_string, date_format)
    return s

time_1 = '2015-08-10 19:33:27'
time_2 = '2015-08-10 19:31:28'
date_format = "%Y-%m-%d %H:%M:%S"
time_1_datetime_object = to_datetime_object(time_1, date_format)
time_2_datetime_object = to_datetime_object(time_2, date_format)

diff_time = time_1_datetime_object - time_2_datetime_object

回答by Bobby Zandavi

timedelta.secondsdoes not represent the total number of seconds in the timedelta, but the total number of seconds modulus 60.

timedelta.seconds不代表timedelta中的总秒数,而是模数60的总秒数。

Call the function timedelta.total_seconds()instead of accessing the timedelta.secondsproperty.

调用函数timedelta.total_seconds()而不是访问timedelta.seconds属性。