Thursday, March 24, 2011

jython + joda-time

joda-time is a date-time library written in Java.  It has advantages over Java's built in time utilities in terms of power and ease of use.  It has some functionality that Python's own datetime library does not.  Here is a sampling from within jython:

[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.7.0-internal
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys

>>> # make sure the jar is in the CLASSPATH
>>> sys.path.append('/home/carl/Downloads/joda-time-1.6.2/joda-time-1.6.2.jar')
>>> from org.joda import time as joda
>>> rightnow = joda.DateTime()
>>> rightnow
>>> rightnow.getZone()

>>> # I'm actually in New Mexico - close enough
>>> rightnow.dayOfWeek().getAsText()
>>> rightnow.monthOfYear().getAsText()
>>> rightnow.getDayOfMonth()

>>> # days are one indexed along with months

>>> # a date from the past
>>> declofindependence = joda.DateTime(1776, 7, 4, 0, 0, 0, 0)

The Period object allows you to count down to dates in the future of count from dates in the past in terms of years, months, and days:

>>> americasage = joda.Period(declofindependence, rightnow)
>>> americasage.getYears()
>>> americasage.getMonths()
>>> americasage.getWeeks()
>>> americasage.getDays()

joda-time can handle dates far into the future as well as those in the far distant past:

>>> farfuture = joda.DateTime(10000, 1, 1, 1, 0, 0, 0)
>>> farfuture.getYear()
>>> farfuture

Like most things Java, joda-time can be a bit more verbose than its Python equivalent.  Still, the ability to get dates beyond 9999 and some of the functionality may make it well worth the trouble.


  1. Safe to assume that joda won't work with CPython, right?

    I could definitely use this—Python's date handling really isn't very good and has hit me in the face a few times. No easy parsing for most date formats (think RFC 822, ISO 8601, and all the mixes used in-between in the XML world), a bare bones (and incomplete?) toolkit for handling time zones, etc…

  2. @Samat - This will just work with jython because jython works will all the Java libraries and runs on the JVM. CPython doesn't have access to that.

  3. My cousin recommended this blog and she was totally right keep up the fantastic work!

    generic nolvadex

  4. @qeniwait Thank you. That is very kind. I am only seeing this now. Sorry I've been such a slug on the blog front. My life took a few dips, but I hope to start producing something useful again. CBT