Date arithmetic in Python

I know this is easy to do in the expression language, but can’t find a good way to add time to a date using Python. I am gathering information from a dataset and want to add a calculated number of hours to one of the date fields, before passing that information into a report dataset.

It would be great if I could just create a script module that took as arguments, a datetime and a number of hours, then returned the new date like the dateadd function does in the expression language. Is there a method in Python to add hours to a date?

I find it easier to use the Java Calendar object (of course, I’m biased b/c I’m more familiar with the Java libraries than the Python ones…) here is how I’d implement a dateadd function:

def dateadd(date, hours): from java.util import Calendar cal = Calendar.getInstance() cal.setTime(date) cal.add(Calendar.HOUR, hours) return cal.getTime()

1 Like

Thanks Carl. That does look pretty easy. I guess I am going to have to learn a little java since it seems like it has a ton of methods and built in functions.

Yeah, Java’s standard library is pretty impressive. (I keep this as an open tab in my web browser 24x7)