6

如果今天 17:00:00 已经过去,那么它应该是今天的日期,否则 - 昨天的。今天我得到的时间:

test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)

但我不想有未来的时间。我该如何解决?

4

4 回答 4

9

您可以检查当前时间是否小于 17:00,如果是,则从生成的时间对象中减去一天:

test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)
if datetime.datetime.now() < test:
    test = test - datetime.timedelta(days=1)
于 2012-10-02T08:27:03.237 回答
3

最好datetime.time直接用今天的比较时间。然后用datetime.timedelta做数学:

if datetime.datetime.now().time() > datetime.time(17,0):
  # today, as it's after 17 o'clock
  test = datetime.date.today()
else:
  # yesterday, as it's before 17 o'clock
  test = datetime.date.today() - datetime.timedelta(days=1)
于 2012-10-02T08:27:16.997 回答
1

根据一天中的时间将测试设置为今天或昨天:

from datetime import datetime, date, timedelta

if datetime.now().strftime('%H:%M') > '17:00':
    test = date.today()
else:
    test = date.today() - timedelta(days=1)
于 2012-10-02T08:47:27.547 回答
0

Python 的 datetime 函数有时确实很不方便。虽然您可以datetime.timedelta为您的案例使用对象,但要减去以天为单位的时间,例如递增月份或年份会变得很烦人。因此,如果您迟早不仅想添加一天,不妨试试这个功能:

import datetime
import calendar    

def upcount(dt, years=0, months=0, **kwargs):
    """ 
    Python provides no consistent function to add time intervals 
    with years, months, days, minutes and seconds. Usage example:

    upcount(dt, years=1, months=2, days=3, hours=4)
    """
    if months:
        total_months = dt.month + months
        month_years, months = divmod(total_months, 12)
        if months == 0:
            month_years -= 1
            months = 12
        years += month_years
    else:
        months = dt.month

    years = dt.year + years
    try:
        dt = dt.replace(year=years, month=months)
    except ValueError:
        # 31st march -> 31st april gives this error
        max_day = calendar.monthrange(years, months)[1]
        dt = dt.replace(year=years, month=months, day=max_day)

    if kwargs:
        dt += datetime.timedelta(**kwargs)
    return dt
于 2012-10-02T08:39:28.533 回答