处理Python日期时间中的月份
我有一个函数,它可以获取给定日期时间之前的月份的开始日期:
def get_start_of_previous_month(dt):
'''
Return the datetime corresponding to the start of the month
before the provided datetime.
'''
target_month = (dt.month - 1)
if target_month == 0:
target_month = 12
year_delta = (dt.month - 2) / 12
target_year = dt.year + year_delta
midnight = datetime.time.min
target_date = datetime.date(target_year, target_month, 1)
start_of_target_month = datetime.datetime.combine(target_date, midnight)
return start_of_target_month
不过,这个方法看起来有点复杂。有没有人能推荐一个更简单的方法?我使用的是Python 2.4。
1 个回答
9
使用一个 timedelta(days=1)
来表示这个月的开始:
import datetime
def get_start_of_previous_month(dt):
'''
Return the datetime corresponding to the start of the month
before the provided datetime.
'''
previous = dt.date().replace(day=1) - datetime.timedelta(days=1)
return datetime.datetime.combine(previous.replace(day=1), datetime.time.min)
.replace(day=1)
会返回一个新的日期,这个日期是当前月的第一天。然后再减去一天,就能确保我们回到上一个月。接着,我们再用同样的方法来获取那个上个月的第一天。
演示(确保在 Python 2.4 上运行):
>>> get_start_of_previous_month(datetime.datetime.now())
datetime.datetime(2013, 2, 1, 0, 0)
>>> get_start_of_previous_month(datetime.datetime(2013, 1, 21, 12, 23))
datetime.datetime(2012, 12, 1, 0, 0)