7

If 17:00:00 today is already passed, then it should be today's date, otherwise - yesterday's. Today's time I get with:

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

But I don't want to have future time. How can I fix it?

LA_
  • 19,823
  • 58
  • 172
  • 308

4 Answers4

13

You could check if the current time is less than 17:00, if so, substract one day from the generated time object:

test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0)
if datetime.datetime.now() < test:
    test = test - datetime.timedelta(days=1)
andrean
  • 6,717
  • 2
  • 36
  • 43
3

Better use the datetime.time of today directly for comparing the times. Then use datetime.timedelta to do the math:

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)
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
1

set test as today or yesterday depending on the time of day:

from datetime import datetime, date, timedelta

if datetime.now().strftime('%H:%M') > '17:00':
    test = date.today()
else:
    test = date.today() - timedelta(days=1)
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
0

Pythons datetime functions are indeed quite unhandy sometimes. While you can use datetime.timedelta objects for your case, to substract times in days, e.g. upcounting month or years becomes annoying. So in case you sooner or later not only want to add one day, maybe give this function a try:

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
Michael
  • 7,316
  • 1
  • 37
  • 63