繁体   English   中英

如何编写返回两个日期之间的天数的 python function

[英]How to write a python function that returns the number of days between two dates

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

我的尝试:

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM