如何在Python中获取每月的下一个特定日期?
我正在使用Python 2.7 我想从现在起得到下一个月的第25天。今天是2月17日,所以我应该是2月25日。如果我们在2月26日,我会在3月25日 我找不到任何关于获取本月下一个特定日期的信息,但我非常确定Python有一些东西可以让它变得简单 有人知道怎么做吗?你可以用它来玩如何在Python中获取每月的下一个特定日期?,python,python-2.7,date,Python,Python 2.7,Date,我正在使用Python 2.7 我想从现在起得到下一个月的第25天。今天是2月17日,所以我应该是2月25日。如果我们在2月26日,我会在3月25日 我找不到任何关于获取本月下一个特定日期的信息,但我非常确定Python有一些东西可以让它变得简单 有人知道怎么做吗?你可以用它来玩rrule: import datetime from dateutil.rrule import * now = datetime.datetime.today().date() days = rrule(MONT
rrule
:
import datetime
from dateutil.rrule import *
now = datetime.datetime.today().date()
days = rrule(MONTHLY, dtstart=now, bymonthday=25)
print (days[0]) # datetime.datetime(2016, 2, 25, 0, 0)
print (days[1]) # datetime.datetime(2016, 3, 25, 0, 0)
导入日期时间
def get_next_date_与_day(每月的第天):
today\u date=datetime.datetime.today()
今天=今天_date.day
如果今天=本月的第天:
今天返回\u日期
如果今天<本月的第天:
return datetime.date(今日日期年、今日日期月、月中日)
如果今天>每月的第天:
如果今天_date.month==12:
返回日期time.date(今天日期年+1,1,当月的第天)
返回日期time.date(今日日期年,今日日期月+1,本月的第二天)
打印获取下一个日期和日期(25)
>>2016-02-25
def获取25天(当前日期):
如果当前日期>2016-02-25
打印第25天(日期时间日期(2016年2月25日))
>> 2016-02-25
打印第25天(日期时间日期(2016年2月26日))
>> 2016-03-25
打印第25天(日期时间日期(2016年12月26日))
>> 2017-01-25
您应该查找包datetime,然后使用datetime对象引用特定日期,您可以使用一个非常简单的例程检查日期是否大于25,如果大于25,则增加月份并将日期设置为25;另一方面,如果小于25,只需将其更新为25。看看这个:如果你想要一个月的下一个30天,你想要得到什么?这一天是否存在(例如2月30日)重要吗?这一天是否存在于您当地的时区(例如,托克劳没有2011年12月30日)(Pacific/Fakaofo
tzid)?您可以在此处省略dtstart
(默认为当前当地时间)。
import datetime
def get_next_date_with_day(day_of_the_month):
today_date = datetime.datetime.today()
today = today_date.day
if today == day_of_the_month:
return today_date
if today < day_of_the_month:
return datetime.date(today_date.year, today_date.month, day_of_the_month)
if today > day_of_the_month:
if today_date.month == 12:
return datetime.date(today_date.year+1, 1, day_of_the_month)
return datetime.date(today_date.year, today_date.month+1, day_of_the_month)
print get_next_date_with_day(25)
>>2016-02-25
def get_25_th_day(curr_date):
if curr_date.day <= 25:
return datetime.date(curr_date.year, curr_date.month, 25)
else:
new_month = curr_date.month + 1
new_year = curr_date.year
if curr_date.month == 12:
new_month = 1
new_year = curr_date.year + 1
return datetime.date(new_year, new_month, 25)
print get_25_th_day(datetime.date.today())
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 25))
>> 2016-02-25
print get_25_th_day(datetime.date(2016, 2, 26))
>> 2016-03-25
print get_25_th_day(datetime.date(2016, 12, 26))
>> 2017-01-25