Home > front end >  How to convert object datetime.time.now() to object datetime.timedelta()?
How to convert object datetime.time.now() to object datetime.timedelta()?

Time:02-24

I'm using the datetime.time.now() for the current time, i.e. I want to perform an operation that counts in the totals of the hours (e.g. 1h:45min - 0h:50min). I cannot convert the current time to the datetime.timedelta object.

CodePudding user response:

There is no datetime.time.now() — you must mean datetime.now() which returns a datetime instance which has a year, month, and day as well as the time of day. If you want a different time on the same day you can use its attributes to construct one.

If you subtract two datetimes the result is a timedelta. You can also subtract an arbitrary timedelta from a datetime (resulting in another datetime).

Note that timedelta instances only have the attributes days, seconds, and microseconds, so if you want to know how long they are in hours and minutes, you have to manually calculate them.

Here's an example of doing all of these things.

from datetime import datetime, timedelta

now = datetime.now()  # Current time.
# Construct a time on the same day.
sunrise = datetime(now.year, now.month, now.day, hour=6, minute=58)

if sunrise > now:  # Future
    delta = sunrise - now
    when = 'will be in'
    ago = ''
else:  # Past
    delta = now - sunrise
    when = 'happened'
    ago = 'ago'

days = delta.days
seconds = delta.seconds
hours = delta.seconds//3600
minutes = (delta.seconds//60) % 60
print(f'sunrise {when} {hours} hours {minutes} minutes {ago}')
print(f'30 minutes before sunrise today is {sunrise - timedelta(minutes=30)}')

CodePudding user response:

I think I've found it; I wanted to compare the current time with the sunrise and sunset that Python itself retrieved. I've done it this way now (so the next one can do it too)

import datetime as dt   
DTN = dt.datetime.now() 

H = int(DTN .strftime("%H")) 
M = int(DTN .strftime("%M"))
S = int(DTN .strftime("%S")) 

t1 = dt.timedelta(hours= H, minutes= M, seconds=S) 
t2 = dt.timedelta(hours= 1, minutes= 0, seconds=0) 

if t1 > t2: 
    timeCal = t1-t2 }

elif t1<t2: 
    timeCal = t2-t1 

else: 
    timeCal = t1 t2 

print(timeCal)

actual time = 20:00:00

result: 19:00:00
  • Related