概述
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?
解决方案
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.
最后
以上就是顺利香菇为你收集整理的python程序员入职第一天_在python中查找每月的第一天的全部内容,希望文章能够帮你解决python程序员入职第一天_在python中查找每月的第一天所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复