Business Scenario:
We often run monthly or weekly levels of reports.
Week level of the report is also relatively OK, that is, seven days ago directly with Timedelta (days=7) to get the start date is OK;
But the monthly level of the report will be troublesome, because timedelta this function does not have the parameter of month, then we how to get a number one months ago, but also to consider how many days this month, will not cross the year, and so on ...
I think of a simple way to share with you today
With this approach, you don't have to judge the difficult logic of a leap year.
If you find any problem with this algorithm, you can point it out and learn together.
1 fromDatetimeImportDate2 fromDatetimeImportTimedelta3 4 defget_last_month_first_day (date):5Date_terminal = 26 +Date.day6Res_date = Date-timedelta (days=date_terminal)7 while1:8 ifRes_date.day = = 1:9 BreakTen Else: OneRes_date-= Timedelta (Days=1) A returnres_date - - the if __name__=='__main__': -test_date_a = Date (2016, 9,3) -Test_date_b = Date (2016, 10, 1) -Test_date_c = Date (2016, 2, 28) +Test_date_d = Date (2016, 1, 1) - Printmap (Get_last_month_first_day, [ +Test_date_a, Test_date_b, Test_date_c, Test_date_d])
How to get the one month number in Python