I'm trying to find the first day of the month in python with one condition: if my current date passed the 25th of the month, then the first date variable will hold the first date of the next month instead of the current month. I'm doing the following:
import datetime
todayDate = datetime.date.today()
if (todayDate - todayDate.replace(day=1)).days > 25:
x= todayDate + datetime.timedelta(30)
x.replace(day=1)
print x
else:
print todayDate.replace(day=1)
is there a cleaner way for doing this?
There are a few ways to do this, but I've gone with the following: last_date = datetime(year, month + 1, 1) + timedelta(days=-1) . This will calculate the first date of the following month, then subtract 1 day from it to get the last date of the current month.
To find the first Monday of a given month, we are going to use the numpy module i.e the numpy. busday_offset() method in numpy module. Parameters: date: The array of dates to process.
You can use the calender module to get the first day of the week using Python. The calender module has a special function, firstweekday(), that returns the current setting for the weekday to start each week.
Can be done on the same line using date.replace
:
from datetime import datetime datetime.today().replace(day=1)
This is a pithy solution.
import datetime todayDate = datetime.date.today() if todayDate.day > 25: todayDate += datetime.timedelta(7) print todayDate.replace(day=1)
One thing to note with the original code example is that using timedelta(30)
will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.
Use dateutil.
from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
first_day = today.replace(day=1)
if today.day > 25:
print(first_day + relativedelta(months=1))
else:
print(first_day)
from datetime import datetime
date_today = datetime.now()
month_first_day = date_today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
print(month_first_day)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With