1. 程式人生 > 實用技巧 >python獲取今天零點和24點以及其他日期

python獲取今天零點和24點以及其他日期

1.獲取今天零點和24點

def getTodayDate():
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                          microseconds=now.microsecond)
    last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
    return zero_today, last_today

2.獲取本週一零點和週日24點

def getWeekDate():
    now = datetime.datetime.now()
    zero_week = now - datetime.timedelta(days=now.weekday(), hours=now.hour, minutes=now.minute, seconds=now.second,
                                         microseconds=now.microsecond)
    last_week = now + datetime.timedelta(days=6 - now.weekday(), hours=23 - now.hour, minutes=59 - now.minute,
                                         seconds=59 - now.second)

    return getFormatDate(zero_week), getFormatDate(last_week)

3.獲取本月一號零點和最後一天24點

def getMonthDate():
    now = datetime.datetime.now()
    zero_month = datetime.datetime(now.year, now.month, 1)
    last_month = datetime.datetime(now.year, now.month + 1, 1) - datetime.timedelta(days=1) + datetime.timedelta(
        hours=23, minutes=59, seconds=59)
    return getFormatDate(zero_month), getFormatDate(last_month)

4.上週第一天和最後一天

now = datetime.datetime.now()
last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)

5.上月第一天和最後一天

last_month_end = this_month_start - timedelta(days=1)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

6.今年/去年第一天和最後一天

this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - datetime.timedelta(days=1)
last_year_end = this_year_start - datetime.timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)