在python中查找每月的第一天 [英] finding first day of the month in python

查看:208
本文介绍了在python中查找每月的第一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下一种条件在python中查找月份的第一天:如果我的当前日期超过了该月的25号,则第一个日期变量将保存下个月的第一个日期,而不是当前日期月。我正在执行以下操作:

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)

有没有更清洁的方法?

推荐答案

这是一个简单的解决方案。

This is a pithy solution.

import datetime 

todayDate = datetime.date.today()
if todayDate.day > 25:
    todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)

在原始代码示例中要注意的一件事是,如果您使用 timedelta(30) 将会造成麻烦测试一月的最后一天。这就是为什么我使用7天的增量。

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.

这篇关于在python中查找每月的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆