【问题标题】:I need the date calculation in Python => Midnight from the previous day to the current time of day我需要 Python => 午夜从前一天到当前时间的日期计算
【发布时间】:2017-07-28 20:08:18
【问题描述】:

我需要在 Python 中计算日期 => 从前一天到当前时间的午夜。

示例:

CURRENT DATE        TRANSFORMATION
28/07/2017 17:00 => 26/07/2017 23:59:59 
26/07/2017 16:00 => 24/07/2017 23:59:59 

尝试了代码,但它不起作用。

代码

import datetime
days_ago = datetime.datetime.now() + datetime.timedelta(days=-1)

【问题讨论】:

  • 这不是圣诞老人的愿望清单,也不是“给我写代码”服务。你必须自己解决这个问题,并遇到你的代码的真正问题
  • 欢迎来到 SO,请确保您已使用 tour,看到 How to Ask,如果您发布一些代码,请使用 minimal reproducible example

标签: python python-2.7 python-3.x


【解决方案1】:

你开始得很好。然后只需更改小时分钟和秒:

import datetime
days_ago = datetime.datetime.now() + datetime.timedelta(days=-1)
days_ago = days_ago.replace(second=59, minute=59, hour=23)

但从你的例子来看,它可能是days=-2

【讨论】:

    【解决方案2】:

    为什么不只计算相关日期的秒数?

    import datetime
    
    now = datetime.datetime.now() # or any other date
    s = now.hour * 3600 + now.minute * 60 + now.second
    print(s) => 38801 at this time
    

    最终您可能会遇到时区问题,具体取决于您要使用的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      相关资源
      最近更新 更多