【问题标题】:How to write a python function that returns the number of days between two dates如何编写一个返回两个日期之间天数的python函数
【发布时间】:2021-07-06 18:59:38
【问题描述】:

我是函数新手,我正在尝试编写一个返回两个日期之间天数的函数:

我的尝试:

import datetime
from dateutil.parser import parse

def get_x_days_ago (date_from, current_date = None):
    td = current_date - parse(date_from)
    if current_date is None:
        current_date = datetime.datetime.today()
    else:
        current_date = datetime.datetime.strptime(date_from, "%Y-%m-%d")
    return td.days

print(get_x_days_ago(date_from="2021-04-10", current_date="2021-04-11"))

预计天数:

1

【问题讨论】:

  • 首先,我强烈建议将日期解析和获取天数的逻辑分开。解决较小的问题会容易得多,并且代码将更具可组合性。所以你的 get_x_days_ago 将得到日期时间对象而不是字符串。

标签: python function datetime parsing


【解决方案1】:

所以似乎存在多个问题,正如我在 cmets 中所说,一个好主意是将解析和逻辑分开。

def get_x_days_ago(date_from, current_date = None):
    if current_date is None:
        current_date = datetime.datetime.today()
    return (current_date - date_from).days
    
# Some other code, depending on where you are getting the dates from. 
# Using the correct data types as the input to the get_x_days_ago (datetime.date in this case) will avoid
# polluting the actual logic with the parsing/formatting.
# If it's a web framework, convert to dates in the View, if it's CLI, convert in the CLI handling code
date_from = parse('April 11th 2020')
date_to = None # or parse('April 10th 2020')
days = get_x_days_ago(date_from, date_to)
print(days)

你得到的错误来自这一行(你应该在回溯中看到)

td = current_date - parse(date_from)

由于 current_date="2021-04-11"(字符串),但 date_from 被解析为 parse(date_from),您正试图从 str 中减去 date

附:如果您既没有 web 也没有 cli,则可以将此解析代码放入 def main 或代码中您首先获取表示日期的初始字符串的任何其他位置。

【讨论】:

    【解决方案2】:

    您似乎已经知道可以从日期时间中减去日期时间。我想,也许,你真的在​​寻找这个:

    https://stackoverflow.com/a/23581184/2649560

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      相关资源
      最近更新 更多