题
我已经写一个时间转换器采取的time_t的系统和将其转换成可读的日期/时间。哦,这是我的第二个Python脚本如初。我们将离开这一事实放在一边,继续前进。
完整脚本托管引擎收录喜。
对于年份和月份文字转换器是相当容易的,但我已经打了一个严重的砖墙试图让一天的工作。正如你所看到的,我一直在试图暴力破解我的方式一路从1970年到今天。不幸的是,一天出来作为-105。
有谁知道一个更好的方式来做到这一点,还是有办法解决了我在这里尝试?它是目前凌晨3:30,所以它很可能我缺少明显的东西。
对不起,我忘了,请注意,我为了学习Python手动这样做。通过日期函数做失败的目的,很遗憾。
解决方案
(我假设你这样做是为了学习Python,所以我会指出你的代码中的错误)。
>>> years = SecondsSinceEpoch / 31540000
Nonononono。你不能做到这一点。有些年份31536000秒,别人31622400秒。
>>> if calendar.isleap(yeariterator) == True:
您不需要测试一个真正的价值是真实的。 :-)执行:
>>> if calendar.isleap(yeariterator):
相反。
另外改变:
>>> yeariterator = 1969
>>> iterator = 0
>>> while yeariterator < yearsfordayfunction:
>>> yeariterator = yeariterator + 1
要:
在范围yeariterator(1970,yearsfordayfunction):
这也将解决您的错误:你不停止,直到2009年以后,所以你得到的答案-105,因为那里为105天了一年的
。和也,有没有在按月计算一个月多一点。年复一年正常工作。
for yeariterator in range(1970, yearsfordayfunction):
if calendar.isleap(yeariterator) == True:
days = days - 366
else:
days = days - 365
和8个空格的缩进是很多。图4是比较常见的。
另外,我会计算一个方法一年一年的一天,而不是做两次。
def YearDay():
SecondsSinceEpoch = int(time.time())
days = SecondsSinceEpoch // 86400 # Double slash means floored int.
year = 1970
while True:
if calendar.isleap(year):
days -= 366
else:
days -= 365
year += 1
if calendar.isleap(year):
if days <= 366:
return year, days
else:
if days <= 365:
return year, days
def MonthDay(year, day):
if calendar.isleap(year):
monthstarts = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
else:
monthstarts = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
month = 0
for start in monthstarts:
if start > day:
return month, day - monthstarts[month-1] + 1
month += 1
其他提示
为什么不使用:
from datetime import datetime
the_date = datetime.fromtimestamp(the_time)
print(the_date.strftime('%Y %B %d'))
日期时间模块处理所有的边缘的情况下 - 闰年,闰秒,飞跃天 - 以及时区转化(带有可选的第二个参数)
您可以做到这一点无论是与 time.strftime
:
>>> import time
>>> time.strftime('%Y %B %d')
'2009 September 18'
>>> import datetime
>>> datetime.date.today().strftime('%Y %B %d')
'2009 September 18'
我还会指出在您发布的代码,一个奇怪的现象:
try:
SecondsSinceEpoch = time.time()
except IOError:
Print("Unable to get your system time!")
1)为什么time.time()
引发IOError异常?据我知道这是不可能的,其功能是产生一个错误,它应该始终返回一个值。
2。)Print
应print
。
3。)即使time.time
确实引发IOError
例外,你吞下例外,你可能不希望这样做。下一行需要SecondsSinceEpoch
被定义,以便将刚刚提出另一项(更混乱)异常。