shrd
shrd

Reputation: 21

How to combine two times in Python using datetime module?

How to sum two times in Python using datetime module? For example 15:33:21.43691 + 01:12:47.65729. Should I use timedelta? Or is there any other way to do that? Thanks!

Upvotes: 1

Views: 810

Answers (2)

JackX
JackX

Reputation: 160

The best way would be to convert the clock time into seconds, add it and then convert it back into time. The edge case would be handling a rollover from 86400 seconds ( 1 full day). You can use the time module from datetime to accomplish this. ( from datetime import time). This way you can add two times from a 24 hour clock. You'll still need to handle the edge case in which the date rolls over, as mentioned before, i.e., the time becomes more than 24 hours. For instance, adding 02:00 o'clock to 23:00 o'clock. The result should be 01:00 on the next day. It's actually quite simple

>>> from datetime import time
>>>
>>> time1 = time(15,33,21,43691)
>>> print(time1)
15:33:21.043691
>>> time1_seconds = time1.hour * 60 * 60 + time1.minute * 60 + time1.second + float( '0.' + str(time1.microsecond))
>>> print(time1_seconds)
56001.43691
>>> time2 = time(1,12,47,65729)
>>> print(time2)
01:12:47.065729
>>> time2_seconds = time2.hour * 60 * 60 + time2.minute * 60 + time2.second + float( '0.' + str(time2.microsecond))
>>> print(time2_seconds)
4367.65729
>>> timeFinal_seconds = time1_seconds + time2_seconds
>>> print(timeFinal_seconds)
60369.0942
>>> timeFinal_seconds = timeFinal_seconds % 86400   #Rolling over incase the day changes,
 i.e, the total time becomes more than 24 hours, the clock completes a full cirle. 23:00 + 2 hours will give 01:00 on the clock
>>> print(timeFinal_seconds)
60369.0942
>>> hours
16.76919283333333
>>> minutes = (timeFinal_seconds % 3600) / 60
>>> minutes
46.15156999999999
>>> seconds = (timeFinal_seconds % 3600 % 60)
>>> seconds
9.094199999999546
>>> microseconds = str(seconds).split('.')[-1]   # nifty trick to extract the decimal part from a number
>>> microseconds
'094199999999546'
>>> Finaltime = time(int(hours),int(minutes),int(seconds),int(microseconds))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
>>> Finaltime = time(int(hours),int(minutes),int(seconds),int(microseconds[0:5]))   # taking the first 5 decimal places only using string manipulation to remove the error above
>>> Finaltime
datetime.time(16, 46, 9, 9419)
>>> print(Finaltime)
16:46:09.009419

Which makes sense, adding 1 hour 12 minutes to 3:33 PM in the afternoon gives 4:46 PM ( which is what you are doing in your question)

If you want explicitly add two dates, you can use the timestamp function of the datetime class to get the date timestamp from 2 dates, and then add the timestamp, and then convert the time stamp back into a date.

The only catch is that timestamp is calculated from Unix time beginning, i.e. January 1st, 1970 at 00:00:00 UTC, which should not really matter because we all need some reference point for time.

So if you add two dates 31st December, 1999 and 31st December 2012, you don't really get the year 4000 but some year 2045 something.

>>> date1 = datetime(1999,12,31)
>>> date2 = datetime(2012,12,31)
>>>
>>> timestamp1 = date1.timestamp()
>>> print(timestamp1)
946578600.0
>>> timestamp2 = date2.timestamp()
>>> print(timestamp2)
1356892200.0
>>>
>>> timestamp_NewDate = timestamp1 + timestamp2
>>>
>>> NewDate = datetime.fromtimestamp(timestamp_NewDate)
>>>
>>> print(NewDate)
2042-12-29 18:30:00
>>>

Upvotes: 0

samusa
samusa

Reputation: 483

Time and date times are points on the time line, so you can only add a timedelta to point in time. The points are relative to the origin datetime.datetime.fromtimestamp(0) >>> datetime.datetime(1970,1,1,1,0).

datetime.datetime.today() + datetime.timedelta(weeks=2)

Upvotes: 2

Related Questions