Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the date of the first of last month(python)

I am trying to find the first date of the previous one months from now using python.
like this ‘2022-06-01’
Can anyone help me with this please?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use datetime.date class to construct the first day of a month. Minus 1 day you will get the last day of the last month, then construct it another datetime.date class to get the first day of last month.

>>> import datetime
>>> def first_day_of_month(d):
...   return datetime.date(d.year, d.month, 1)
...
>>> def last_day_of_last_month():
...   return first_day_of_month(datetime.date.today()) - datetime.timedelta(days=1)
...
>>> def first_day_of_last_month():
...   return first_day_of_month(last_day_of_last_month())
...
>>> print(first_day_of_last_month())
2022-06-01
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading