Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding first day of the month in python

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?

like image 814
tkyass Avatar asked May 23 '16 16:05

tkyass


People also ask

How do I get the first and last day of the current month in Python?

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.

How do you get the first Monday of the month in Python?

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.

How do you get the first day of the week in Python?

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.


4 Answers

Can be done on the same line using date.replace:

from datetime import datetime  datetime.today().replace(day=1) 
like image 172
Gustavo Eduardo Belduma Avatar answered Sep 23 '22 14:09

Gustavo Eduardo Belduma


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.

like image 24
andrew Avatar answered Sep 21 '22 14:09

andrew


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)
like image 22
lampslave Avatar answered Sep 21 '22 14:09

lampslave


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)
like image 36
Balaji.J.B Avatar answered Sep 20 '22 14:09

Balaji.J.B