finding first day of the month in python

2020-05-25 03:51发布

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?

10条回答
劳资没心,怎么记你
2楼-- · 2020-05-25 04:25

Yes, first set a datetime to the start of the current month.

Second test if current date day > 25 and get a true/false on that. If True then add add one month to the start of month datetime object. If false then use the datetime object with the value set to the beginning of the month.

import datetime 
from dateutil.relativedelta import relativedelta

todayDate = datetime.date.today()
resultDate = todayDate.replace(day=1)

if ((todayDate - resultDate).days > 25):
    resultDate = resultDate + relativedelta(months=1)

print resultDate
查看更多
我命由我不由天
3楼-- · 2020-05-25 04:26

Can be done on the same line

from datetime import datetime

datetime.today().replace(day=1)
查看更多
▲ chillily
4楼-- · 2020-05-25 04:26

Use arrow.

import arrow
arrow.utcnow().span('month')[0]
查看更多
Juvenile、少年°
5楼-- · 2020-05-25 04:28

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)
查看更多
登录 后发表回答