算术日期时间对象

时间:2013-01-15 09:59:20

标签: python

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

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

1 个答案:

答案 0 :(得分:4)

您可以执行以下操作

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)