用定义的函数实现一些方程

2024-05-29 05:59:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 从1900到99的整数
  • 月(1到12之间的1或2位整数)
  • 日(1到31之间的1或2位整数,取决于月份)。在

我定义了这个函数,并使用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

目前我的代码:

^{pr2}$

Tags: 函数代码for定义整数mathexcel公式
1条回答
网友
1楼 · 发布于 2024-05-29 05:59:02

对于这种情况,最好使用标准库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的优点是您有一个标准接口,该接口具有多种方法,可以将字符串解析为日期或时间:

^{pr2}$

相关问题 更多 >

    热门问题