Mr.Unknown21
Mr.Unknown21

Reputation: 35

Python: TimeDate Issue

I have been making a small countdown timer to a specific time, but it seems to have a issue of negative days. Example:

s1 = '14:00:00'
s2 = str(current_time)
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s1, FMT) - datetime.strptime(s2, FMT)
print tdelta
>>>-1 day, 22:34:23

Current_time is my System time

How can I remove the -1 day? Neither string (s1 or s2) has days, so its making this day figure within the tdelta variable calculation.

Upvotes: 1

Views: 101

Answers (1)

Serbitar
Serbitar

Reputation: 2224

If you know the day the target time should be (like 2014,8,1) use it:

import datetime
target_time = datetime.datetime(2014, 8, 1, 14, 0, 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

If the target time is today, you can just change hour, minute and second and leave the rest from todays date:

import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

If the target_time is before the current time, the timedelta object tracks the negative time by using negative days and positive seconds that are decreasing and thus increase the negative difference and thus the time distance to the target_time.

If you always want to track the time to a given hour, regardless of day, use:

import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
if target_time < now:
    target_time += datetime.timedelta(1)
time_to_go = target_time - now
print(time_to_go)

Upvotes: 1

Related Questions