-3

请我需要你的帮助,我正在尝试编写一个 PYTHON 代码,该代码使用一个名为 calcExcelDate 的已定义函数来实现一些等效于指定日期的 excel 日期等式:

  • 年(从 1900 到 9999 的 4 位整数);
  • 月(从 1 到 12 的 1 或 2 位整数);
  • 日(从 1 到 31 的 1 或 2 位整数,取决于月份)。

我定义了函数并使用了 3 个循环来指定上述给定的年、月和日范围。但是如何使用该函数来实现以下方程:

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_
4

1 回答 1

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')
于 2013-10-18T09:12:23.333 回答