【Python】Python判断统计每个月天数源码示例

如何利用Python判断统计每个月天数源。在日常的学习或是工作中会经常遇到需要统计日期数据的情况。特别是统计涉及到自然周或是自然月的计算。

用Python编程语言来统计这些是需要考虑很多条件的。例如:自动运行的时候我们需要判断每个月的天数,而且对于自然月的加减,还要考虑跨年的自然月与是否闰年。
这是一个用python写的小程序,可以计算自然周与自然月。是通过时间戳计算,返回时间戳;
如果计算天则返回当天凌晨的时间戳;
如果计算周则返回当周周一的凌晨时间戳;
自然月则返回当月1日凌晨时间戳。

代码不是很好看,但效果还是不错的。

断统计每个月天数源码示例:如下

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
计算自然周第一天、自然月第一天和每天的凌晨时间戳
//www.iplaypy.com/
"""
import time
def get_day_begin(ts = time.time(),N = 0):
    """
    N为0时获取时间戳ts当天的起始时间戳,N为负数时前数N天,N为正数是后数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时获取时间戳ts当周的开始时间戳,N为负数时前数N周,N为整数是后数N周,此函数将周一作为周的第一天
    """
    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时获取时间戳ts当月的开始时间戳,N为负数前数N月,N为正数后数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)))


大家在学python的时候肯定会遇到很多难题,以及对于新技术的追求,这里推荐一下我们的Python资源分享秋秋裙:855408893  内有安装包,学习视频资料,免费直播实战案例。这里是Python学习者的聚集地,零基础,进阶,都欢迎每日分享一些学习的方法和需要注意的小细节

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69913713/viewspace-2649419/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69913713/viewspace-2649419/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值