练手——用Python写的时间戳转换为北京时间的小工具

#北京时间需加上8小时
bj = 8*3600

def time_stamp(times):
    #一天总秒数
    nonDaySeconds = 24*3600
    leapmonths = [31,29,31,30,31,30,31,31,30,31,30,31]
    nonleapmonths = [31,28,31,30,31,30,31,31,30,31,30,31]
    #四年为一个周期,从1972年开始
    fourYearDays = (366+365+365+365)

    year = 0
    currentDays = 0
    sumDay = 0
    month = 0


    #计算自1970年以来经过的天数
    nDays = int(times/nonDaySeconds)
    #计算当天已经过了多少毫秒
    currentDaySeconds = times%nonDaySeconds

    #计算自1973年以来经过的多少个完整4年周期,并计算上一个闰年是哪一年
    lastLeapYear = int((nDays-(365+365+366))/fourYearDays)*4+(1970+2)
    #计算不足一个4年周期的天数
    lDays = (nDays-(365+365+366))%fourYearDays
    #print(lastLeapYear,lDays)
    #判断当前属于四年周期的哪一年,并计算当年已经走过的总天数
    if lDays < 365:
        year = 1
        currentDays = lDays
    elif lDays< (365+365):
        year = 2
        currentDays = lDays - 365
    elif lDays < (365+365+365):
        year = 3
        currentDays = lDays - 365 - 365
    elif lDays < (365+365+365+366):
        year = 4
        currentDays = lDays - 365 - 365 - 365
    currentYear = lastLeapYear + year
    #print(currentYear,currentDays)

    #计算几月几号
    if year == 4:
        #如果是闰年
        for i in range(len(leapmonths)):
            if sumDay <= currentDays:
                sumDay += leapmonths[i]
                month += 1
        day = (currentDays - sumDay + 1) + leapmonths[month-1]
    else:
        for i in range(len(nonleapmonths)):
            if sumDay <= currentDays:
                sumDay += nonleapmonths[i]
                month += 1
        day = (currentDays - sumDay + 1) + nonleapmonths[month-1]
    #print(month,day)


    #计算时分秒
    currentHour = int(currentDaySeconds/(60*60))
    currentMinute = int((currentDaySeconds%(60*60))/60)
    currentSeconds = (currentDaySeconds%(60*60))%60
    #print(currentHour,currentMinute,currentSeconds)
    print(str(currentYear)+' 年 '+judgetime(month)+' 月 '+judgetime(day)+' 日   '+
        judgetime(currentHour)+':'+judgetime(currentMinute)+':'+judgetime(currentSeconds))


def judgetime(value):
    if value < 10:
        return '0' + str(value)
    else:
        return str(value)

转载于:https://www.cnblogs.com/Hinglam/p/9284047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值