Issue
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
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
Answered By - WeDBA
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.