Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python time + timedelta equivalent

Tags:

python

I'm trying to do something like this:

time() + timedelta(hours=1) 

however, Python doesn't allow it, apparently for good reason.

Does anyone have a simple work around?

Related:

  • What is the standard way to add N seconds to datetime.time in Python?
like image 921
Antonius Common Avatar asked Mar 17 '09 22:03

Antonius Common


People also ask

How does Python compare to Timedelta?

You can also find the difference between two datetime objects to get a timedelta object and perform the comparison based on the positive or negative value returned by the timedelta. total_seconds() function. if seconds < 0: print('First date is less than the second date.

How does Python calculate Timedelta?

To calculate the total time difference in seconds, use the total_seconds() method on the timedelta object time_diff . tsecs = time_diff.

What is datetime Timedelta in Python?

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.


2 Answers

The solution is in the link that you provided in your question:

datetime.combine(date.today(), time()) + timedelta(hours=1) 

Full example:

from datetime import date, datetime, time, timedelta  dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30) print dt.time() 

Output:

00:25:00 
like image 99
jfs Avatar answered Sep 21 '22 10:09

jfs


If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime >>> from datetime import timedelta >>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36) >>> afternoon nptime(13, 0) >>> str(afternoon) '13:00:00' 

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

like image 21
rescdsk Avatar answered Sep 17 '22 10:09

rescdsk