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?
You can use dateutil.rrule:
My solution to find the first and last day of the current month:
The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.
In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.
This is a pithy solution.
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.This could be an alternative to Gustavo Eduardo Belduma's answer: