A Pythonic Date
Posted by at 18:03 on 08 Mar 2009. There are ? Comments

Handling dates in Python sucks. Full stop. There is nothing pythonic about datetime.datetime and datetime.timedelta, and using them is a real pain when you just want to do simple little things like getting the timestamp from the first of this month, or just adding or subtracting a day or week from the built-in datetime's read-only properties, a fairly common thing to do in accounting and payment systems.

<p>iCal, because dates <strong>should</strong> be this easy

iCal, because dates should be this easy

I've written a replacement Date object which should make life easier. The only dependency is dateutil. It is a pure Python module and tries to be easy to use and modify to your needs, thought most of what you want should already be there. My main goals for this object were the following:

  • Make it easy to make a Date from anything - a timestamp, date, datetime, tuple, etc.
  • Make it easy to turn a Date into anything
  • Make it easy and pythonic to add/subtract one or more days, weeks, months, or years
  • Make it easy to get a tuple of the start and end of the month

Here are some examples of use before I paste the code (I name the module date.py):

from date import Date
d = Date()
# Get a timestamp
ts = d.timestamp
# Get a time tuple
mytuple = d.tuple
# Get a date
mydate = d.date
# Get a datetime
mydatetime = d.datetime
# Get a tuple of timestamps of the beginning and end of the month
begin, end = [x.timestamp for x in d.month_tuple]
# Set the date to yesterday
d.day -= 1
# Get a Date from yesterday directly
d = Date(days_ago = 1)
# Get the timestamp of the beginning of the day of yesterday
ts = Date(days_ago = 1).start_of_day.timestamp

You get the idea. All methods are properly documented so just take a look at what is available. The code was listed here previously but I've now made it public in a proper version repository:



blog comments powered by Disqus