问题
I'm trying to make some kind of "deadline clock" in python. There is lot of topics about time difference calculations and I followed some and put together this kind of code:
import datetime
from dateutil.relativedelta import relativedelta
# Get current time:
today = datetime.date.today()
timenow = datetime.datetime.now()
current_time = str(today) + " " + str(timenow.strftime("%H:%M:%S"))
# Set deadline:
deadline = "2019-12-12 15:00:00"
# Calculate difference:
start = datetime.datetime.strptime(current_time,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')
diff = relativedelta(ends, start)
print("Now: " + current_time)
print("Deadline: " + deadline)
print(str(diff.days) + " days. "
+ str(diff.hours) + " hours. "
+ str(diff.minutes) + " minutes. "
+ str(diff.seconds) + " seconds. "
)
But the problem is, that it will allways show just maximum of one month difference... So where is the problem?
回答1:
Just substract your start date with the end date.
import datetime
today = datetime.date.today()
timenow = datetime.datetime.now()
deadline = "2019-12-12 15:00:00"
current_time = str(today) + " " + str(timenow.strftime("%H:%M:%S"))
start = datetime.datetime.strptime(current_time,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')
print(start - ends)
As suggested in the comments, you don't really need to to use both .today()
and .now()
separately, .now()
returns the current date and time as a datetime object itself.
import datetime
timenow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
deadline = "2019-12-12 00:00:00"
start = datetime.datetime.strptime(timenow,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')
print(start - ends)
来源:https://stackoverflow.com/questions/58391143/how-much-time-left-to-given-date-days-hours-mins-s