2011-12-25 5 views
1

ユーザーは自分のインタフェースで時と分を指定しています。 Pythonのdatetimeオブジェクトに現在の日付を添付したいと思います。そして、私が試したPythonで指定された時と分に現在の日を追加します。

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") 

これは動作しますが、それは醜いだ

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

しかし、この利回り:

まず、私はこれを試してみました確かに良い方法がありますか?

答えて

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) 
関連する問題