python获取月的第一天和上个月的同一天

import datetime, time

def lastMonth(date):
    year = date.year
    month = date.month
    day = date.day
    if month == 1 :
        month = 12
        year -= 1
    else :
        month -= 1
    if day == 31 and month in (4,6,9,11):
        day = 30
    if day > 28 and month == 2:
        day = 29 if year % 4 == 0 else 28

    last_beginday = datetime.datetime.strptime('%s-%s-%s'%(year, month, day), '%Y-%m-%d')
    last_sameday = datetime.datetime.strptime('%s-%s-%s %s:%s:%s'%(year, month, day, date.hour, date.minute, date.second), '%Y-%m-%d %H:%M:%S')
    last_begin_timestamp = last_beginday.strftime('%s')
    last_sameday_timestamp = last_sameday.strftime('%s')
    return last_begin_timestamp, last_sameday_timestamp

def get_current_day_timestamp():
    time_string = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')
    timestamp = time.mktime(datetime.datetime.strptime(time_string, "%Y-%m-%d").timetuple())
    return timestamp

last_begin_timestamp, last_sameday_timestamp = lastMonth(datetime.datetime.fromtimestamp(time.time()))
current_day_timestamp = get_current_day_timestamp()
print(last_begin_timestamp, last_sameday_timestamp, current_day_timestamp)

推荐阅读更多精彩内容