从python中的日期时间减去秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24025552/
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 03:51:01  来源:igfitidea点击:

Subtract seconds from datetime in python

pythondatetimepython-3.x

提问by rodrigocf

I have an int variable that are actually seconds (lets call that amount of seconds X). I need to get as result current date and time (in datetime format) minus Xseconds.

我有一个实际上是秒的 int 变量(让我们称之为秒数X)。我需要得到当前日期和时间(以日期时间格式)减去X秒的结果。

Example

例子

If Xis 65 and current date is 2014-06-03 15:45:00, then I need to get the result 2014-06-03 15:43:45.

如果X是 65 并且当前日期是2014-06-03 15:45:00,那么我需要得到结果2014-06-03 15:43:45

Environment

环境

I'm doing this on Python 3.3.3 and I know I could probably use the datetimemodule but I haven't had any success so far.

我正在 Python 3.3.3 上执行此操作,我知道我可能可以使用该datetime模块,但到目前为止我还没有取得任何成功。

采纳答案by julienc

Using the datetimemodule indeed:

datetime确实使用该模块:

import datetime

X = 65
result = datetime.datetime.now() - datetime.timedelta(seconds=X)

You should read the documentationof this package to learn how to use it!

你应该阅读这个包的文档来学习如何使用它!

回答by wim

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2014, 6, 3, 22, 55, 9, 680637)
>>> now - timedelta(seconds=15)
datetime.datetime(2014, 6, 3, 22, 54, 54, 680637)

That's a core library solution, generally for this task I prefer to use a 3rd party class with dateutil.relativedelta, it has more parameters and greater flexibility.

这是一个核心库解决方案,通常对于这个任务,我更喜欢使用 3rd 方类dateutil.relativedelta,它有更多的参数和更大的灵活性。

回答by AlienFromCA

To expand on @julienc's answer, (in case it is helpful to someone)

扩展@julienc的答案,(以防它对某人有帮助)

If you allow X to accept positive or negatives, and, change the subtraction statement to an addition statement, then you can have a more intuitive (so you don't have to add negatives to negatives to get positives) time adjusting feature like so:

如果您允许 X 接受正数或负数,并且将减法语句更改为加法语句,那么您可以拥有更直观的(因此您不必将负数添加到负数以获得正数)时间调整功能,如下所示:

def adjustTimeBySeconds(time, delta):
    return time + datetime.timedelta(seconds=delta)

time = datetime.datetime.now()
X = -65
print(adjustTimeBySeconds(time, X))
X = 65
print(adjustTimeBySeconds(time, X))