2

I'm writing a program that needs to be able to handle multiple calendars (mainly the standard “proleptic Gregorian” and the "365 day" (no leap) calendars). The python datetime module handles the Gregorian calendar out of the box but I'd like to also have it handle other calendars.

A short example:

from datetime import datetime
import calendar

def example(year):
    delta = datetime(year, 3, 1) - datetime(year, 2, 28)
    print '%i is a leap year: %s' % (year, calendar.isleap(year))
    print 'Days between 2-28 and 3-1: %s' % delta.days

example(2012)
2012 is a leap year: True
Days between 2-28 and 3-1: 2
example(2013)
2013 is a leap year: False
Days between 2-28 and 3-1: 1

This is certainly the intended operation of the module but it doesn't serve my particular needs. I'd like to be able to set the calendar to 'noleap' and retain the functionality of datetime and timedelta.

I'm wondering if anyone have any experience defining/using a custom calendar with datetime?

martineau
  • 119,623
  • 25
  • 170
  • 301
jhamman
  • 5,867
  • 19
  • 39

1 Answers1

1

If you wrote functions that could convert date-times from one calendar system to another, then you can do things by first converting all inputs to the standard Gregorian calendar, doing the desired math or operation, and then convert the results back to the other system. This would likely be the least amount of work and least error-prone -- assuming your conversion functions work correctly.

Update: Just discovered a module on pypi named julian that looks like it could be used to do this.

martineau
  • 119,623
  • 25
  • 170
  • 301