首页 > 解决方案 > 如何生成包含时间的日期?

问题描述

我正在尝试生成具有范围的日期,但未显示时间。代码如下:

def date_range(start, end, step: datetime.timedelta):
   while start < end:
   yield start
   start += step


  for d in date_range(
    start=datetime.date(2019, 1, 1),
    end=datetime.date(2019, 1, 15),
    step=datetime.timedelta(days=7),
    ):
    print(d)



  >>>2019-01-01
  >>>2019-01-08

该代码仅显示日期而不显示时间。为什么???

标签: pythondatetime

解决方案


datetime.date()根据此处的 Python 文档,您正在使用它不包含时间信息 - 它只是将小时/分钟/秒设置为 0。

我想你想使用datetime.datetime()包含时间信息的。

有关更多信息, 请参阅Python 文档。datetime.datetime()


推荐阅读