gpt4 book ai didi

python - 日期时间对象的算术

转载 作者:行者123 更新时间:2023-11-28 22:57:53 25 4
gpt4 key购买 nike

http://docs.python.org/2/library/datetime.html

我使用 today 函数获取当前日期,如何对该对象执行简单的算术运算,以便我可以将当​​前日期减少或增加 1 或 2(即昨天或前天)

最佳答案

您可以执行以下操作

In [6]: import datetime

# Today
In [7]: datetime.datetime.now()
Out[7]: datetime.datetime(2013, 1, 15, 15, 31, 10, 760000)

# Tomorrow's date
In [8]: print datetime.datetime.now() + datetime.timedelta(days=1)
2013-01-16 15:31:15.336000

# Day after tomorrow's day
In [9]: print datetime.datetime.now() + datetime.timedelta(days=2)
2013-01-17 15:31:52.601000

# Yesterday's date
In [10]: print datetime.datetime.now() - datetime.timedelta(days=1)
2013-01-14 15:32:00.081000

也适用于 datetime.datetime.today()

In [15]: datetime.datetime.today()
Out[15]: datetime.datetime(2013, 1, 15, 15, 34, 37, 55000)

In [16]: datetime.datetime.today() + datetime.timedelta(days=1)
Out[16]: datetime.datetime(2013, 1, 16, 15, 34, 47, 560000)

关于python - 日期时间对象的算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com