loops - Python: Find date beginning two months prior to today AND start on a Monday -
so beginner python , have been working datetime, time, , timedelta libraries little bit. trying create piece of code gives me date approximately 2 months ago(exact_two_months_date) today (whatever today happens be). catch is, want find date approx. 2 months ago , begin actual start_date on monday of week. in theory, actual start date not 2 months ago. week beginning on monday 2 months ago today.
example pseudocode: today = '20150425' ## '%y%m%d' ... saturday exact_two_months_date = '20150225' ## 2 months ago ... wednesday start_date = '20150223' ## monday of week 2 months ago
so how find 'start_date' above? if day 2 months ago begins on saturday or sunday, want go next monday. hope clear , makes sense... once find start date, increment day day(only week days) 'today'.
appreciate feedback, thanks.
calculating dates using python-dateutil
if dependency on third-party package option, ☞ python-dateutil
provides convenient method calculate dates.
browse docs ☞ relativedelta see wealth of supported parameters. more calculations package needs dates, more helper module dateutil
justifies dependency. more inspiration on has offer see ☞ examples page.
quick run-through:
>>> import datetime >>> dateutil.relativedelta import relativedelta >>> today = datetime.date.today() >>> two_m_ago = today - relativedelta(months=2) >>> # print two_m_ago ~> datetime.date(2015, 2, 25) >>> monday = two_m_ago - datetime.timedelta(days=two_m_ago.weekday()) >>> # print monday ~> datetime.date(2015, 2, 23)
getting monday weekday()
once have date 2 months ago in variable two_m_ago
, subtract index of weekday()
it. index 0
monday , goes way 6
sunday. if two_m_ago
monday, subtracting 0
not cause changes.
Comments
Post a Comment