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?
CodePudding user response:
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
CodePudding user response:
You could use python-dateutil
:
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2022, 7, 19, 1, 29, 40, 680122)
>>> previous_month = now - relativedelta(months=1)
>>> previous_month
datetime.datetime(2022, 6, 19, 1, 29, 40, 680122)
>>> previous_month_first_day = previous_month.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
>>> previous_month_first_day
datetime.datetime(2022, 6, 1, 0, 0)
CodePudding user response:
To parse the date, you can split the string and put the integers in variables.
ymd = '2022-06-01'.split('-')
year = int(ymd[0])
month = int(ymd[1]) # you don't need day because day is always 1
Then you can do the subtraction
month -= 1
if month == 0:
month = 12
year -= 1
Finally, you can put the result back to the string
sy = '0'*(4-len(str(year))) str(year)
sm = '0'*(2-len(str(month))) str(month)
print(f'{sy}-{sm}-01') # prints 2022-05-01
CodePudding user response:
Arrow is a great library for handling dates, time, timestamps and timezones.
>>> import arrow
>>> arrow.now().shift(months=-1).floor('month')
<Arrow [2022-06-01T00:00:00-05:00]>