有没有办法通过datetime
pd.Timestamp
获取此[周/月/季度/年]最后一天的日期(datetime
,pandas
或同等水平){ {1}}或其他日期&时间利用?
答案 0 :(得分:4)
您可以向pandas.DateOffset
,DateTimeIndex
或Timestamp
或datetime.date
添加datetime.datetime
:
dates = pd.date_range('2015-8-13', periods=4, freq='3D')
# DatetimeIndex(['2015-08-13', '2015-08-16', '2015-08-19', '2015-08-22'],
# dtype='datetime64[ns]', freq='3D', tz=None)
捕捉到一周的最后一天(例如,星期天):
In [232]: dates+offsets.Week(weekday=6)
Out[232]: DatetimeIndex(['2015-08-16', '2015-08-23', '2015-08-23', '2015-08-23'], dtype='datetime64[ns]', freq=None, tz=None)
截至本月的最后一天:
In [207]: dates+offsets.MonthEnd()
Out[207]: DatetimeIndex(['2015-08-31', '2015-08-31', '2015-08-31', '2015-08-31'], dtype='datetime64[ns]', freq=None, tz=None)
赶上本季度的最后一天:
In [212]: dates+offsets.QuarterEnd()
Out[215]: DatetimeIndex(['2015-09-30', '2015-09-30', '2015-09-30', '2015-09-30'], dtype='datetime64[ns]', freq=None, tz=None)
赶到一年的最后一天:
In [219]: dates+offsets.YearEnd()
Out[222]: DatetimeIndex(['2015-12-31', '2015-12-31', '2015-12-31', '2015-12-31'], dtype='datetime64[ns]', freq=None, tz=None)
请注意,添加偏移量始终会使日期前进。例如,2015-08-16是星期日,添加offsets.Week(weekday=6)
会使它在2015-08-23:
In [233]: pd.Timestamp('2015-8-16')+offsets.Week(weekday=6)
Out[233]: Timestamp('2015-08-23 00:00:00')
为防止这种情况发生,您可以从dates
In [234]: dates - offsets.Day() + offsets.Week(weekday=6)
Out[237]: DatetimeIndex(['2015-08-16', '2015-08-16', '2015-08-23', '2015-08-23'], dtype='datetime64[ns]', freq=None, tz=None)
答案 1 :(得分:2)
仅使用datetime
。
>>> d = datetime.date.today()
一周的最后一天:
# This was wrong earlier.
>>> d + datetime.timedelta(days=5 - d.weekday())
datetime.date(2015, 8, 15)
每月的最后一天:
>>> datetime.date(year=(d.year + int(d.month % 12 == 0)), month=(d.month + 1) % 12, day=1) - datetime.timedelta(days=1)
datetime.date(2015, 8, 31)
季度的最后一天:
>>> datetime.date(year=d.year, month=((d.month % 3) + 1) * 3 + 1, day=1) - datetime.timedelta(days=1)
datetime.date(2015, 9, 30)
一年的最后一天:
>>> datetime.date(year=d.year, month=12, day=31)
datetime.date(2015, 12, 31)
编辑:这一切都非常难看,使用更高级别的第三方库可能是最好的,除非有令人信服的理由不(并且似乎没有在这里)。
答案 2 :(得分:2)
import datetime
from dateutil.relativedelta import relativedelta, SU
def last_day_of_week(year, week_num):
# assuming sunday is the last day of week
# weeks= is an offset, hence the minus one
return datetime.date(year, 1, 1) + relativedelta(weekday=SU(1), weeks=week_num - 1)
def last_day_of_month(year, month):
return datetime.date(year, month, 1) + relativedelta(months=1, days=-1)
def last_day_of_year(year):
return datetime.date(year, 1, 1) + relativedelta(years=1, days=-1)