python time now and before

Viewed 48

how i can do the checking. so that if the time which i write in the h m s format hasnt yet come, add yesterdays date to it

for example: now 00:10:15 , i input 00:15:15 bot write 2022-09-09 00:15:15

and if the time has come to add todays

for example: now 00:10:15 , i input 00:10:00 , bot write 2022-09-10 00:10:00

from datetime import datetime, timezone
import time
from zoneinfo import ZoneInfo
import pytz

#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))

newYorkTz = pytz.timezone("Europe/Kiev") 
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d ')
#date = datetime.today().strftime('%Y-%m-%d ')
from_date = str(input('time): '))


fulldate = timeInNewYork + from_date

dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
epoch = dt.timestamp() 

print(epoch)
1 Answers

You need to add an if.. else statement to check if the input time has passed (compared to the actual time) or not. If so, you can use timedelta to add one day and get your timestamp.

Try this :

from datetime import datetime, timezone, timedelta
import time
from zoneinfo import ZoneInfo
import pytz

#date = datetime.now(ZoneInfo("Pacific/Kwajalein"))

newYorkTz = pytz.timezone("Europe/Kiev") 
timeInNewYork = datetime.now(newYorkTz).strftime('%Y-%m-%d')
#date = datetime.today().strftime('%Y-%m-%d ')

now = datetime.now(newYorkTz)

from_date = str(input('time): '))
my_datetime = datetime.strptime(from_date, "%H:%M:%S")
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)

fulldate = timeInNewYork + ' ' + from_date

if (now > my_datetime):
    dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S')
    epoch = dt.timestamp() 
else:
    dt = datetime.strptime(fulldate, '%Y-%m-%d %H:%M:%S') + timedelta(days=-1)
    epoch = dt.timestamp() 

print(dt)
print(epoch)

>>> Test with a past time

time):  11:55:33
2022-09-10 11:55:33
1662803733.0

>>> Test with a future time

time):  19:00:33
2022-09-09 19:00:33
1662915633.0
Related