Python 获取本月第一天和上月第一天
整体流程
首先,我们需要导入datetime模块,然后利用datetime模块中的方法来获取本月第一天和上个月第一天的日期。
下面是整个实现过程的步骤:
步骤 | 操作 |
---|---|
1 | 导入datetime模块 |
2 | 获取当前日期 |
3 | 获取本月第一天 |
4 | 获取上个月第一天 |
具体操作步骤及代码
步骤1:导入datetime模块
import datetime
步骤2:获取当前日期
current_date = datetime.date.today()
步骤3:获取本月第一天
first_day_of_current_month = current_date.replace(day=1)
步骤4:获取上个月第一天
if current_date.month == 1:
last_month = 12
last_year = current_date.year - 1
else:
last_month = current_date.month - 1
last_year = current_date.year
first_day_of_last_month = datetime.date(last_year, last_month, 1)
完整代码示例
import datetime
# 获取当前日期
current_date = datetime.date.today()
# 获取本月第一天
first_day_of_current_month = current_date.replace(day=1)
# 获取上个月第一天
if current_date.month == 1:
last_month = 12
last_year = current_date.year - 1
else:
last_month = current_date.month - 1
last_year = current_date.year
first_day_of_last_month = datetime.date(last_year, last_month, 1)
print("本月第一天:", first_day_of_current_month)
print("上月第一天:", first_day_of_last_month)
类图
classDiagram
class datetime{
__init__(self)
today()
}
datetime : +__init__(self)
datetime : +today()
通过以上步骤和代码,你可以成功获取本月第一天和上个月第一天的日期。希望对你有所帮助,加油!