更有效的编码方式?

时间:2011-10-15 03:43:26

标签: python date

我应该得到2011年12月1日的excel日期和星期几,并以此格式打印出来。 2011年12月1日星期四的Excel日期是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"

任何帮助将不胜感激:)

3 个答案:

答案 0 :(得分:4)

怎么样:

days = ['sun', 'mon', 'tue', 'wed', 'thur', 'fri', 'sat']

print days[Day_Of_week]

另请看一下:How do I read a date in Excel format in Python?

答案 1 :(得分:0)

“”“我应该得到2011年12月1日的excel日期”“”:没有 Excel日期这样的东西。有两个“ Excel中使用的日期系统,其中一个是1900年的时期[Windows Excel中的默认值],另一个是1904 [Windows的Mac默认值]。

xlrd documentation;有一个关于日期的部分,并查看其名称中包含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

答案 2 :(得分: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)