python get first/last day of month

To get the first day of a month, you can use Python's datetime module. Here is a sample code showing how to get the first day of the current month:

from datetime import datetime

# 获取当前日期和时间
now = datetime.now()

# 获取当前月份的第一天
first_day_of_month = datetime(now.year, now.month, 1)

# 打印结果
print("当前日期和时间:", now)
print("当前月份的第一天:", first_day_of_month)

The output will be similar to the following:

当前日期和时间: 2023-05-12 15:30:00
当前月份的第一天: 2023-05-01 00:00:00

Note that the above code will use the current system date and time to get the first day of the current month. You can also manually specify the date and time to get the first day of a specific month as follows:

from datetime import datetime

# 指定日期和时间
date_string = "2023-09-15"
date = datetime.strptime(date_string, "%Y-%m-%d")

# 获取指定月份的第一天
first_day_of_month = datetime(date.year, date.month, 1)

# 打印结果
print("指定日期:", date)
print("指定月份的第一天:", first_day_of_month)

The output will be similar to the following:

指定日期: 2023-09-15 00:00:00
指定月份的第一天: 2023-09-01 00:00:00

To get the last day of a month, you can use Python's datetime and calendar modules. Here is a sample code showing how to get the last day of the current month:

from datetime import datetime
import calendar

# 获取当前日期和时间
now = datetime.now()

# 获取当前月份的最后一天
last_day_of_month = calendar.monthrange(now.year, now.month)[1]

# 构造最后一天的日期对象
last_day = datetime(now.year, now.month, last_day_of_month)

# 打印结果
print("当前日期和时间:", now)
print("当前月份的最后一天:", last_day)

The output will be similar to the following:

当前日期和时间: 2023-05-12 15:30:00
当前月份的最后一天: 2023-05-31 00:00:00

Note that the above code will use the current system date and time to get the last day of the current month. You can also manually specify the date and time to get the last day of a specific month, like so:

from datetime import datetime
import calendar

# 指定日期和时间
date_string = "2023-09-15"
date = datetime.strptime(date_string, "%Y-%m-%d")

# 获取指定月份的最后一天
last_day_of_month = calendar.monthrange(date.year, date.month)[1]

# 构造最后一天的日期对象
last_day = datetime(date.year, date.month, last_day_of_month)

# 打印结果
print("指定日期:", date)
print("指定月份的最后一天:", last_day)

The output will be similar to the following:

指定日期: 2023-09-15 00:00:00
指定月份的最后一天: 2023-09-30 00:00:00

Guess you like

Origin blog.csdn.net/iuv_li/article/details/130865824