2011-12-25 23 views
1

用戶在我的界面中指定小時和分鐘。我想將當前日期附加到Python中的datetime對象。在Python中將當前日添加到指定的小時和分鐘

首先我嘗試這樣做:

a = datetime.strptime("8:30pm", "%I:%M%p") 
print a 

但這種收益率:

1900-01-01 20:30:00 

然後我嘗試:

b = date.today() 
a = datetime.strptime(str(b.year) + "-" + str(b.month) + "-" 
         + str(b.day) + " 8:30pm", "%Y-%m-%d %I:%M%p") 

這工作,但它的醜陋;當然有更好的方法?

回答

4

是,使用datetime.datetime.combine

import datetime 
a = datetime.datetime.strptime("8:30pm", "%I:%M%p") 
today = datetime.datetime.today() 

result = datetime.datetime.combine(today.date(), a.time()) 

# result == datetime.datetime(2011, 12, 25, 20, 30) 
相關問題