How to get the one month number in Python

Source: Internet
Author: User
Tags timedelta

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.