2017-08-20 6 views
-3

現在の日時を取得し、時刻を00:00:00に設定しようとしています。 datetime.now()の時刻を設定する

はこれを行うには、私が呼ぶ:

current_date = dt.datetime.now() 
current_date.replace(hour=0, minute=0, second=0) 
print(current_date) 

出力は次のようになります。

私が期待するものではありません
2017-08-20 10:43:56.3243245 

。私がしなければしかし、:

2017-08-20 00:00:00 

なぜこれがある:私は期待して、私は結果を得るよう

current_date = dt.datetime(dt.datetime.now().date().year,dt.datetime.now().date().month,dt.datetime.now().date().day,0,0,0) 

すべてがありますか?何が起こっている?? replaceはなぜ機能しないのですか?あなたが行う必要がありますので

+0

が、それは*あなたが無視する新しいオブジェクトを返します*;: あなたが行う必要がありますので、それは、新しいdatetime型のインスタンスを返します。それは突然変異操作ではありません。 docs:https://docs.python.org/3/library/datetime.html#datetime.datetime.replaceをご覧ください。また、日付のために 'date.today()'を使うこともできます。 – jonrsharpe

答えて

1

replaceは、新しいdatetimeインスタンスを返します。

>>> current_date = dt.datetime.now() 
>>> current_date = current_date.replace(hour=0, minute=0, second=0, microsecond=0) 
>>> print(current_date) 
2017-08-20 00:00:00 

あなたはまた、それを正確に00:00:00ようにするためにmicrosecond=0を交換する必要があります。

0

replaceメソッドは、置換後も常に新しい値を返します。その値を格納する必要があります。

は、それはあなたのケースでのように

を交換した後、新しい値を返します覚えておいてください。それは作業を行い

current_date = dt.datetime.now() 
current_date = current_date.replace(hour=0, minute=0, second=0) 
print(current_date) 
関連する問題