今天或昨天如何获得时间17:00:00?

时间:2012-10-02 08:19:00

标签: python datetime

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

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

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

4 个答案:

答案 0 :(得分:4)

您可以检查当前时间是否小于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)

答案 1 :(得分: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)

答案 2 :(得分: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)

答案 3 :(得分:0)

Pythons日期时间函数有时确实非常不方便。虽然您可以在案例中使用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
相关问题