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
2011-03-24T19:54:45.544-06:00
>>> rightnow.getZone()
America/Edmonton

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

>>> # 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()
234
>>> americasage.getMonths()
8
>>> americasage.getWeeks()
2
>>> americasage.getDays()
6



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()
10000
>>> farfuture
10000-01-01T01:00:00.000-07:00
>>>


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.

3 comments:

  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…

    ReplyDelete
  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.

    ReplyDelete
  3. @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

    ReplyDelete