user1762447 user1762447 - 2 years ago 191
Python Question

finding first day of the month in python

I'm trying to find the first day of the month in python with one condition which is 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 like the following:

import datetime
todayDate =
if (todayDate - todayDate.replace(day=1)).days > 25:
x= todayDate + datetime.timedelta(30)
print x
print todayDate.replace(day=1)

is there a cleaner way for doing this?

Thanks in advance!

Answer Source

This is a pithy solution.

import datetime 

todayDate =
if > 25:
    todayDate =  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download