我需要你的帮助,我正在尝试编写一个PYTHON代码,该代码使用名为calcExcelDate的已定义函数来实现某些指定日期等效的excel日期方程式:
我定义了这个函数并使用了3个for循环来指定上面给出的年,月和日范围。但是如何使用该函数来实现以下方程式:
y_2 = year - 1900
em = math.floor((14 - month) / 12)
y_3 = y_2 - em
m_2 = month + 12 * em
I_ = 1 + min(y_3, 0) + math.floor(y_3 / 4) - math.floor(y_3 / 100) + math.floor((y_3 + 300) / 400)
d_1 = math.floor(-1.63 + (m_2 - 1) * 30.6)
d_2 = day + y_3 * 365 + I_ + d_1
到目前为止我的代码:
import time
import math
DAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
FULL_MONTHS = ("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December")
mm_ = tuple(str(date) for date in range(2013-10-17, 2100-01-01)) # a tuple of character strings containing dates in the date range Excel supports,
# such as ("2013-Oct-17", "2100-01-01")
print mm_
def calcExcelDate(year, month, day):
for year in range(1900, 10000):
for month in range(1, 13):
for day in range(1, 32):
y_2 = year - 1900
em = math.floor((14 - month) / 12)
y_3 = y_2 - em
m_2 = month + 12 * em
I_ = 1 + min(y_3, 0) + math.floor(y_3 / 4) - math.floor(y_3 / 100)
+ math.floor((y_3 + 300) / 400)
d_1 = math.floor(-1.63 + (m_2 - 1) * 30.6)
d_2 = day + y_3 * 365 + I_ + d_1
xx_ = calcExcelDate(2010, 10, 1)
print xx_
答案 0 :(得分:0)
对于类似这样的事情,最好使用标准库datetime作为您希望处理的日期和时间的接口,然后根据需要将它们转换为Excel序列日期。
以下代码显示了如何在XlsxWriter模块中将datetime
日期转换为Excel日期。
def _convert_date_time(self, dt_obj):
# We handle datetime .datetime, .date and .time objects but convert
# them to datetime.datetime objects and process them in the same way.
if isinstance(dt_obj, datetime.datetime):
pass
elif isinstance(dt_obj, datetime.date):
dt_obj = datetime.datetime.fromordinal(dt_obj.toordinal())
elif isinstance(dt_obj, datetime.time):
dt_obj = datetime.datetime.combine(self.epoch, dt_obj)
else:
raise TypeError("Unknown or unsupported datetime type")
# Convert a Python datetime.datetime value to an Excel date number.
delta = dt_obj - self.epoch
excel_time = (delta.days
+ (float(delta.seconds)
+ float(delta.microseconds) / 1E6)
/ (60 * 60 * 24))
# Special case for datetime where time only has been specified and
# the default date of 1900-01-01 is used.
if dt_obj.isocalendar() == (1900, 1, 1):
excel_time -= 1
# Account for Excel erroneously treating 1900 as a leap year.
if not self.date_1904 and excel_time > 59:
excel_time += 1
return excel_time
使用datetime
的优点是你有一个标准接口,有各种方法可以将字符串解析为日期或时间:
my_datetime = datetime.datetime.strptime('2013-01-23', '%Y-%m-%d')