您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Python中怎么判斷統(tǒng)計(jì)每個(gè)月的天數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
斷統(tǒng)計(jì)每個(gè)月天數(shù)源碼示例:如下
#!/usr/bin/python # -*- coding: utf-8 -*- """ 計(jì)算自然周第一天、自然月第一天和每天的凌晨時(shí)間戳 //www.iplaypy.com/ """ import time def get_day_begin(ts = time.time(),N = 0): """ N為0時(shí)獲取時(shí)間戳ts當(dāng)天的起始時(shí)間戳,N為負(fù)數(shù)時(shí)前數(shù)N天,N為正數(shù)是后數(shù)N天 """ return int(time.mktime(time.strptime(time.strftime('%Y-%m-%d',time.localtime(ts)),'%Y-%m-%d'))) + 86400*N def get_week_begin(ts = time.time(),N = 0): """ N為0時(shí)獲取時(shí)間戳ts當(dāng)周的開始時(shí)間戳,N為負(fù)數(shù)時(shí)前數(shù)N周,N為整數(shù)是后數(shù)N周,此函數(shù)將周一作為周的第一天 """ w = int(time.strftime('%w',time.localtime(ts))) return get_day_begin(int(ts - (w-1)*86400)) + N*604800 def get_month_begin(ts = time.time(),N = 0): """ N為0時(shí)獲取時(shí)間戳ts當(dāng)月的開始時(shí)間戳,N為負(fù)數(shù)前數(shù)N月,N為正數(shù)后數(shù)N月 """ month_day = {1:31,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} cur_y,cur_m,cur_d = [int(x) for x in time.strftime('%Y-%m-%d',time.localtime(ts)).split('-')] if (cur_y%4 == 0 and cur_y%100 != 0) or cur_y%400 == 0: month_day[2] = 29 else: month_day[2] = 28 t = get_day_begin(ts) - (cur_d-1)*86400 real_month = N + cur_m if real_month == cur_m: return t if N > 0: if real_month <= 12: for x in xrange(cur_m,real_month): t += month_day[x]*86400 if real_month > 12: for x in xrange(cur_m,13): t += month_day[x]*86400 t = get_month_begin(t,real_month - 13) if N < 0: if real_month >= 1: for x in xrange(real_month,cur_m): t -= month_day[x]*86400 if real_month < 1: for x in xrange(1,cur_m): t -= month_day[x]*86400 t -= month_day[12]*86400 t = get_month_begin(t,real_month) return t if __name__ == "__main__": t = time.time() print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(get_day_begin(t,1))) print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(get_week_begin(t,-2))) print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(get_month_begin(t,-3)))
看完上述內(nèi)容,你們對(duì)Python中怎么判斷統(tǒng)計(jì)每個(gè)月的天數(shù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。