2012-10-02 178 views
1

如果今天17:00:00已經通過,那麼它應該是今天的日期,否則 - 昨天。 今天的時間我得到:如何獲得時間今天或昨天17:00:00?

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

但我不希望有將來的時間。我該如何解決它?

+0

使它請問每個問題一個問題。 – moooeeeep

+0

@moooeeeep,fixed - http://stackoverflow.com/questions/12686991/how-to-get-last-friday –

回答

4

你可以檢查當前的時間小於17,如果是這樣,從產生的時間對象。減去第一天:

test = datetime.datetime.now().replace(hour=17,minute=0,second=0,microsecond=0) 
if datetime.datetime.now() < test: 
    test = test - datetime.timedelta(days=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) 
0

蟒蛇日期時間函數確實挺不方便的時候。儘管您可以使用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 
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) 
相關問題