【问题标题】:Given two datetime objects, find the months/days in between?给定两个日期时间对象,找出其间的月/日?
【发布时间】:2022-01-02 15:34:43
【问题描述】:

在python中,我需要的是,给定两个日期;

date1 = '2021-11-03'
date2 = '2022-01-02'

我想生成一个介于两者之间的每一天的列表作为日期时间对象,所以一个列表

days_between = ['2022-01-01', '2021-12-31', '2021-12-30', etc, etc]

我还需要找到两者之间的月份,所以在这种情况下,我想要一个带有 say.. 的列表。

months_between = ['2022-01-01', '2021-11-01', '2021-12-01']

现在,我一直在使用类似的东西来完成这个;

# Get all lessons
lessons = get_lessons_between(start=start, end=end, obj=True)

# Store the dates
dates = []
for lesson in lessons:
    date = convert_to_dt_obj(lesson.date)

    if date not in dates:
        dates.append(date)

series = {}

for date in dates:
    for lesson in lessons:
        if convert_to_dt_obj(lesson.date) == date:
            if lesson.date not in series.keys():
                series[lesson.date] = lesson.value
            else:
                series[lesson.date] += lesson.value

tmp_lst = []
for k, v in series.items():
    tmp_lst.append([k, v])

我正在处理的是数据库中的日期,其格式为“YYYY-MM-DD”。我正在尝试在我的前端使用 APEX 图表/vue 对某些图表的数据进行规范化。

我更喜欢将日期作为任意两个日期之间的列表,并根据列表中的每个日期在数据库中查找,这样我就可以说..

for day in days_between:
    .. do some database queries

感谢任何想法或帮助。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    部分答案(仅几天):

    python3.9
    Python 3.9.5 (default, Nov 23 2021, 15:27:38) 
    [GCC 9.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from datetimerange import DateTimeRange
    >>> date1 = '2021-11-03'
    >>> date2 = '2022-01-02'
    >>> DateTimeRange(date1,date2).get_timedelta_second()/(3600*24)
    60.0
    

    【讨论】:

    • 被接受为答案,因为你指出的模块给了我我需要的东西.. 对于其他寻找答案的人,你可以这样做; # for t in time_range.range(relativedelta(months=+1)) 的月份:# 使用 days=1 表示天数 print(t)
    猜你喜欢
    • 2018-01-31
    • 2018-04-11
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多