私はPythonで2回の比較をお探しです。 1回はコンピュータからのリアルタイムであり、もう1回は"01:23:00"
のようなフォーマットの文字列で保存されます。Pythonの現在の時刻と他の時刻との比較
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print "foo"
私はPythonで2回の比較をお探しです。 1回はコンピュータからのリアルタイムであり、もう1回は"01:23:00"
のようなフォーマットの文字列で保存されます。Pythonの現在の時刻と他の時刻との比較
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print "foo"
import datetime
now = datetime.datetime.now()
my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")
# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
if (now > my_datetime):
print "Hello"
EDIT:
上記の溶液は、アカウントの飛躍を考慮していなかった二日(23:59:60
)。
import datetime
import calendar
import time
now = datetime.datetime.now()
my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now
my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")
my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))
if (now > my_datetime):
print "Foo"
https://docs.python.org/2/library/datetime.html
datetime
モジュールを比較することができるオブジェクトに日付、時刻、または組み合わせ日付時刻値を解析します。
from datetime import datetime
current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12
mytime = "10:12:34"
if current_time > mytime:
print "Time has passed."
文字列は辞書順に比較されます。私はdatetimeオブジェクトを比較する必要がありますと思います。 – felipeptcho
@felipeptcho一般的に、それははるかに良いことです。それは正確で、おそらくより速いことが保証されています。この具体的なケースでは、記述された方法で行うのはおそらく「安全」です。 – Vatine
@Vatineおそらく効率が低いにもかかわらず、あなたのソリューションがあまり冗長ではないことがわかります。それはいいです!しかし、なぜそれが "おそらくもっと安全"なのか不思議です。 – felipeptcho
あなたの質問の形式を修正し、それに加えて、それは質問のように見えるようにしてください(現時点では、単一の疑問符がありません):下記のようなケースを扱う更新されたバージョンです。あなたのコードとその中でうまくいかないものを説明してください。 –
なぜあなたは日時の文字列を比較しようとしていますか?これらの文字列は辞書順に比較されるため、間違った答えを与えることがよくあります。なぜそれらを残したり、datetimeオブジェクトに変換して直接比較することができますか? – AChampion