[英]More Efficient way to code this?
我应该获得Excel的2011年12月1日日期和星期几,并以这种格式打印出来。 Excel的日期为2011年12月1日,星期四为40878。我已经能够同时获得两者,但我认为使用if语句获得一天的方法不是最好的方法。 这是我的原始脚本文件,因此请原谅。 我已经检查过,并且知道解决方案正确。 我唯一的问题是获得一种更有效的方式来获得一天以及有关如何在最终输出中获得月份的任何建议。 我们还没有完成日期时间模块,所以我无法尝试。
这是我的代码:
Year=2011
Month=12
Day=1
Y2=Year-1900
en=int((14-Month)/12)
Y3=Y2-en
m2=Month+12*
l=1+min(Y3,0)+int(Y3/4)-int(Y3/100)+int((Y3+300)/400)
d1=int(-1.63+(m2-1)*30.6)
import math
d2=math.floor(Day+Y3*365+l+d1) #d2 is the final excel date.
Day_Of_Week=((d2%7)-1)
print "%s"%(d2)
if Day_Of_Week==0:
print "sun"
if Day_Of_Week ==1:
print "mon"
if Day_Of_Week==2:
print"tue"
if Day_Of_Week==3:
print "wed"
if Day_Of_Week==4 :
print "thur"
if Day_Of_Week==5:
print "fri"
if Day_Of_Week==6:
print "sat"
任何帮助将不胜感激 :)
怎么样:
days = ['sun', 'mon', 'tue', 'wed', 'thur', 'fri', 'sat']
print days[Day_Of_week]
还请看一下: 如何在Python中读取Excel格式的日期?
“”“我应该得到2011年12月1日的Excel的日期”“”:有是Excel 的日期。“有两个”,在使用Excel,一个使用日期系统中的时代是在1900年没有这样的事情[ Windows Excel中的默认设置),另一个使用1904 [Mac中Windows的默认设置。
见xlrd文档 ; 在前面有一个关于日期的部分,并查看名称中带有xldate
的函数。
>>> import xlrd
>>> xlrd.xldate.xldate_from_date_tuple((2011,12, 1), 0) # Windows origin
40878.0
>>> xlrd.xldate.xldate_from_date_tuple((2011,12, 1), 1) # Mac origin
39416.0
感谢您的所有帮助,我能够以更好的方式做到这一点,但是直到我们的作业评分完毕后才能发布。
这就是我所做的:
from math import floor
def calcExcelDate(Year, Month,Day):
Yr_Offset=Year-1900 #Determines year offset from starting point.
Early_Mnth_Correctn=int((14-Month)/12)
#Early month correction:makes the year have 14 months so the leap day is added at the end of the year
DateCorrector=(Yr_Offset)-(Early_Mnth_Correctn) #Corrects Date
MonthCorrector=Month+12*Early_Mnth_Correctn #Corrects Month
Leapyr_Calc=1+min(DateCorrector,0)+int(DateCorrector/4)-int(DateCorrector/100)+int ((DateCorrector+300)/400)
#calculates no of leap years since starting point
char=int(floor(-1.63+(MonthCorrector-1)*30.6))
#determines the number of days preceding the given month in a non leap year.
Excel_Date=(Day+DateCorrector*365+Leapyr_Calc+char )
Days=["Monday","Tuesday","Wednesday","Thursday","Friday","saturday","sunday"]
Months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
Offset=2
dayNo=(Excel_Date-Offset)%7
dayOfWk=Days[dayNo]
return "The excel date of %r %r-%r-%r is %r"%(dayOfWk,Day,Months[Month-1],Year,Excel_Date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.