有没有一种简单的方法可以在 Python 中将 datetime 对象增加一个月?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35066588/
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
Is there a simple way to increment a datetime object one month in Python?
提问by d0rmLife
So I am trying to find a way to increment a datetime object by one month. However, it seems this is not so simple, according to this question.
所以我试图找到一种方法将 datetime 对象增加一个月。然而,根据这个问题,这似乎并不那么简单。
I was hoping for something like:
我希望是这样的:
import datetime as dt
now = dt.datetime.now()
later = now + dt.timedelta(months=1)
But that doesn't work. I was also hoping to be able to go to the same day (or the closest alternative) in the next month if possible. For example, a datetime object set at January 1st would increment to Feb 1st whereas a datetime object set at February 28th would increment to March 31st as opposed to March 28th or something.
但这不起作用。如果可能的话,我还希望能够在下个月的同一天(或最近的替代方案)。例如,设置在 1 月 1 日的日期时间对象将增加到 2 月 1 日,而设置在 2 月 28 日的日期时间对象将增加到 3 月 31 日,而不是 3 月 28 日或其他日期。
To be clear, February 28th would (typically) map to March 31st because it is the last day of the month, and thus it should go to the last day of the month for the next month. Otherwise it would be a direct link: the increment should go to the day in the next month with the same numbered day.
需要明确的是,2 月 28 日(通常)会映射到 3 月 31 日,因为它是该月的最后一天,因此它应该到下个月的最后一天。否则,它将是一个直接链接:增量应转到下个月具有相同编号的那一天。
Is there a simple way to do this in the current release of Python?
在当前版本的 Python 中是否有一种简单的方法可以做到这一点?
采纳答案by Rolf of Saxony
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
检查from dateutil.relativedelta import *
为日期添加特定的时间量,您可以继续使用timedelta
简单的东西,即
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
或者你可以开始使用 relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
下个月最后一天:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
现在这将提供 29/02/2016
for the penultimate day of next month:
下个月的倒数第二天:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
下个月的最后一个星期五:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
下个月的第二个星期二:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
这绝不是可用内容的详尽列表。文档可在此处获得:https: //dateutil.readthedocs.org/en/latest/
回答by Ihor Mudryi
>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)
EDIT: Fails on
编辑:失败
y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month
Ther is no simple way to do it, but you can use your own function like answered below.
没有简单的方法可以做到这一点,但您可以使用自己的功能,如下所述。
回答by taleinat
Note:This answer shows how to achieve this using only the datetime
and calendar
standard library (stdlib) modules - which is what was explicitly asked for. The accepted answer shows how to better achieve this with one of the many dedicated non-stdlib libraries. If you can use non-stdlib libraries, by all means do so for these kinds of date/time manipulations!
注意:这个答案显示了如何只使用来实现这个datetime
和calendar
标准库(STDLIB)模块-这就是被明确提出的要求。接受的答案显示了如何使用许多专用的非 stdlib 库之一更好地实现这一目标。如果您可以使用非 stdlib 库,请务必对此类日期/时间操作进行操作!
How about this?
这个怎么样?
def add_one_month(orig_date):
# advance year and month by one month
new_year = orig_date.year
new_month = orig_date.month + 1
# note: in datetime.date, months go from 1 to 12
if new_month > 12:
new_year += 1
new_month -= 12
new_day = orig_date.day
# while day is out of range for month, reduce by one
while True:
try:
new_date = datetime.date(new_year, new_month, new_day)
except ValueError as e:
new_day -= 1
else:
break
return new_date
EDIT:
编辑:
Improved version which:
改进版本:
- keeps the time information if given a datetime.datetime object
- doesn't use try/catch, instead using
calendar.monthrange
from thecalendar
module in the stdlib:
- 如果给定 datetime.datetime 对象,则保留时间信息
- 不使用 try/catch,而是使用
calendar.monthrange
来自calendar
stdlib 中的模块:
import datetime
import calendar
def add_one_month(orig_date):
# advance year and month by one month
new_year = orig_date.year
new_month = orig_date.month + 1
# note: in datetime.date, months go from 1 to 12
if new_month > 12:
new_year += 1
new_month -= 12
last_day_of_month = calendar.monthrange(new_year, new_month)[1]
new_day = min(orig_date.day, last_day_of_month)
return orig_date.replace(year=new_year, month=new_month, day=new_day)
回答by erol yeniaras
Question: Is there a simple way to do this in the current release of Python?
问题:在当前版本的 Python 中是否有一种简单的方法可以做到这一点?
Answer: There is no simple (direct) way to do this in the current release of Python.
答:在当前版本的 Python 中没有简单(直接)的方法来做到这一点。
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
参考:请参阅docs.python.org/2/library/datetime.html8.1.2 节。时间增量对象。从中我们可以理解,我们不能直接增加月份,因为它不是一个统一的时间单位。
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
另外:如果您想要第一天 -> 第一天和最后一天 -> 最后一天映射,您应该针对不同的月份分别处理。