在python中找到一个月的第一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37396329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:20:32  来源:igfitidea点击:

finding first day of the month in python

pythondatetime

提问by tkyass

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:

我试图用一个条件在 python 中找到当月的第一天:如果我的当前日期超过了当月的 25 日,那么第一个日期变量将保存下个月的第一个日期而不是当前月份。我正在做以下事情:

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?

有没有更干净的方法来做到这一点?

回答by Gustavo Eduardo Belduma

Can be done on the same line

可以在同一条线上完成

from datetime import datetime

datetime.today().replace(day=1)

回答by andrew

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.

原始代码示例需要注意的一点是,如果您在 1 月的最后一天进行测试,使用timedelta(30)会导致问题。这就是我使用 7 天增量的原因。

回答by lampslave

Use dateutil.

使用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)

回答by mba12

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.

第二次测试当前日期天 > 25 并得到一个真/假。如果为 True,则在月​​初日期时间对象中添加一个月。如果为 false,则使用 datetime 对象,其值设置为月初。

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

回答by Balaji.J.B

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)

回答by ImPerat0R_

Use arrow.

使用箭头

import arrow
arrow.utcnow().span('month')[0]

回答by Bill Bell

The arrowmodule will steer you around and away from subtle mistakes, and it's easier to use that older products.

箭头模块将围绕客场引导你从细微的错误,它更容易使用较旧的产品。

import arrow

def cleanWay(oneDate):
    if currentDate.date().day > 25:
        return currentDate.replace(months=+1,day=1)
    else:
        return currentDate.replace(day=1)


currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))

currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))

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.

例如,在这种情况下,您无需考虑不同的月份长度。这是此脚本的输出。

25-Feb-2017 01-Feb-2017
28-Feb-2017 01-Mar-2017

回答by tjurkan

This could be an alternative to Gustavo Eduardo Belduma's answer:

这可能是古斯塔沃·爱德华多·贝尔杜马 (Gustavo Eduardo Belduma) 回答的替代方案:

import datetime 
first_day_of_the_month = datetime.date.today().replace(day=1)

回答by dtatarkin

You can use dateutil.rrule:

您可以使用dateutil.rrule

In [1]: from dateutil.rrule import *

In [2]: rrule(DAILY, bymonthday=1)[0].date()
Out[2]: datetime.date(2018, 10, 1)

In [3]: rrule(DAILY, bymonthday=1)[1].date()
Out[3]: datetime.date(2018, 11, 1)

回答by mhyousefi

My solution to find the first and last day of the current month:

我找到当月的第一天和最后一天的解决方案:

def find_current_month_last_day(today: datetime) -> datetime:
    if today.month == 2:
        return today.replace(day=28)

    if today.month in [4, 6, 9, 11]:
        return today.replace(day=30)

    return today.replace(day=31)


def current_month_first_and_last_days() -> tuple:
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    first_date = today.replace(day=1)
    last_date = find_current_month_last_day(today)
    return first_date, last_date