【问题标题】:Convert range of two date time's into a list of dates and count of seconds per that date python将两个日期时间的范围转换为日期列表和每个日期的秒数python
【发布时间】:2017-11-06 01:04:15
【问题描述】:

我有兴趣创建一个函数,该函数将两个以下datetime 对象(开始日期和结束日期)作为输入并返回一个元组列表。我想要开始和结束日期之间的每个日期的元组,以及该日期的秒数。例如:

import datetime
#there are total 86400 seconds within a date
start_date=datetime.datetime(2017, 10, 17,22,30,0) # this has 60*60+60*30= 5400 within that date
end_date=datetime.datetime(2017, 10, 19,10,30,11) # this date has  10*60*60+60*30+11=37811 seconds

desired_list_of_tupple=[(datetime.datetime(2017, 10, 17),5400),(datetime.datetime(2017, 10, 18),86400),(datetime.datetime(2017, 10, 19),37811)]

对于 2017-10-17,秒数是 5400(22:30 到午夜之间的秒数。

对于 2017-10-18,秒数是 86400(全天在范围内)。

对于 2017-10-19,秒数是 37811(从午夜到 10:30:11 的秒数)。

在这方面的任何帮助都会很棒!

【问题讨论】:

  • # this has 60*60+60*30= 5400 within that date 这是什么意思?为什么日期会有 x 秒的“秒数”?
  • 我会编辑问题

标签: python datetime


【解决方案1】:

尝试以下方法:

from datetime import timedelta

def date_range(start, end):                               
    current = start
    while True:
        next_stop = (current + timedelta(days=1)).replace(
            hour=0, minute=0, second=0)
        if next_stop > end:
            next_stop = end
        yield current.date(), (next_stop - current).total_seconds()
        if next_stop == end:
            break
        current = next_stop

这是一个生成器函数,因此您需要执行list(date_range(start_date, end_date)) 来获取列表。

我没有正确测试边缘情况(例如 end_date 是同一天或更早于开始日期等),我不确定您想要什么,但您指定数据的输出是正确的。根据您的用例,请注意夏季夏令时区周围的问题 - 为此您需要“时区感知”日期时间对象。

【讨论】:

猜你喜欢
  • 2013-08-11
  • 1970-01-01
  • 2023-03-30
  • 2017-05-14
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
相关资源
最近更新 更多