栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

在python用time函数计算GMT 时间和北京时间

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在python用time函数计算GMT 时间和北京时间

# -*- coding = utf-8 -*-
# @Author:Lc_cL
# @Time :2021/10/9
# @file : time.py
# @Software : PyCharm
import time
current_time = time.time()
current_year = int(1970 + current_time/60/60/24/365)  #计算今年是多少年
#print(current_year)    结果为2021
i= int(0);  j = int(0)         #i代表平年, j代表闰年
for year in range(1970,current_year):    #计算平年和闰年
    if (year % 4 != 0):
        i += 1
    else:
        j += 1
past_second = i*365*24*60*60 + j*366*24*60*60       #1970到今年初的秒数
this_year_past_second = current_time - past_second    #今年过去的秒数
day = int(this_year_past_second/60/60/24)    #今年过去的天数
hour = int((this_year_past_second - day*24*60*60)/60/60)        #今天过去的小时数
minute = int((this_year_past_second - day*24*60*60 - hour*60*60)/60)     #这个小时过去的分钟数
second = int(this_year_past_second - day*24*60*60 - hour*60*60 - minute*60)      #这分钟过去的秒数
print(str.format("GMT时间为:{0:<2}:{1:<2}:{2:<2}",hour,minute,second))

beijing_hour = int((this_year_past_second +8*60*60 - day*24*60*60)/60/60)   #北京时间=GMT时间+8h
if (beijing_hour >=24):             #但是如果GMT时间在16点至24点时,北京时间为24点到32点
    beijing_hour = beijing_hour - 24    #所以需要将北京时间返还
print(str.format("北京时间为:{0:<2}:{1:<2}:{2:<2}",beijing_hour,minute,second))

大一新生,这是老师布置的作业

自己慢慢琢磨的,感觉这个算法可能很蠢,希望以后我能几行代码就能解决

刚玩csdn不久,代码中注释得比较详细,所以就不多介绍了

仅供参考,如有错误,请多指教

--------------------------------------------------------------------------------------------------------------------------------

又想了一下不用那么复杂:

# -*- coding = utf-8 -*-
# @Author:Lc_cL
# @Time :2021/10/10
# @file : TIME.py
# @Software : PyCharm
import time
current_time = time.time()
past_day = int(current_time/60/60/24)      #1970到现在过去的天数
hour = int((current_time - past_day*24*60*60)/60/60)    #今天过去的小时数
miunte = int((current_time - past_day*24*60*60 - hour*60*60)/60)   #这个小时过去的分钟数
secend = int((current_time - past_day*24*60*60 - hour*60*60 - miunte*60))  #这分钟过去的秒数
print(str.format("GMT时间为:{0:<2}:{1:<2}:{2:<2}",hour,minute,second))

beijing_hour = int(hour + 8)   #北京时间=GMT时间+8h
if (beijing_hour >=24):             #但是如果GMT时间在16点至24点时,北京时间为24点到32点
    beijing_hour = beijing_hour - 24
print(str.format("北京时间为:{0:<2}:{1:<2}:{2:<2}",beijing_hour,minute,second))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/313685.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号