简体   繁体   English

如何编写从给定日期返回 30 天前的日期的 python function

[英]How to write a python function that returns date 30 days ago from given date

Hi I am new to python and I am trying to write a function that returns the date 30 days ago from a given date.嗨,我是 python 的新手,我正在尝试编写一个 function 从给定日期返回 30 天前的日期。 My function has two parameters as seen below:我的 function 有两个参数,如下所示:

import datetime

def get_date_x_days_ago (x_days_ago, date_from = None):
    d = datetime.timedelta(days=x_days_ago)
    if date_from is None:
        date_from = datetime.today()
    else:
        datetime.datetime.strptime(date_from, "YYYY-mm-dd")

    return date_from - d

print(get_date_x_days_ago(x_days_ago=30, date_from="2020-11-11"))

I cant seem to get the function to work as expected我似乎无法让 function 按预期工作

You need to assign the parsed date from strptime to the date_from variable.您需要将解析后的日期从strptime分配给date_from变量。

Also, see https://www.programiz.com/python-programming/datetime/strptime (under "Format Code List") for the corresponding date format codes, ie "%Y" denotes year with century.另外,相应的日期格式代码参见https://www.programiz.com/python-programming/datetime/strptime (在“格式代码列表”下),即“%Y”表示年份和世纪。

import datetime

def get_date_x_days_ago (x_days_ago, date_from = None):
    d = datetime.timedelta(days=x_days_ago)
    if date_from is None:
        date_from = datetime.datetime.today()
    else:
        date_from = datetime.datetime.strptime(date_from, "%Y-%m-%d")
        # ^^^^ missing assignment

    return date_from - d

print(get_date_x_days_ago(x_days_ago=30, date_from="2020-11-11"))

Since you're finding a certain date from a date to x day before.因为您要找到从某个日期到 x 天前的某个日期。 So, first, convert your date_from to only date then subtract with x_days .因此,首先,将您的date_from转换为仅日期,然后用x_days减去。

from datetime import timedelta, datetime, date
def get_date_x_days_ago(x_days_ago, date_from=None):
    return datetime.strptime(date_from, '%Y-%m-%d').date() - timedelta(x_days_ago) if date_from else date.today()-timedelta(x_days_ago)

print(get_date_x_days_ago(x_days_ago=30, date_from="2020-11-11"))

Output Output

get_date_x_days_ago(x_days_ago=30, date_from="2020-11-11")
2020-10-12

get_date_x_days_ago(x_days_ago=30)
2021-03-12

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

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