Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full-featured date and time library

Tags:

python

c

datetime

I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:

  • Microsecond resolution
  • Daylight savings
    • Example: it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.
    • I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.
  • Custom date ranges
    • The ability to create specialized business calendars that skip over weekends and holidays.
  • Custom time ranges
    • The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.
  • Arithmetic
    • Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes).
  • Natural boundary alignment
    • Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc.

I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.

I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.

like image 258
Mr Fooz Avatar asked Sep 18 '09 02:09

Mr Fooz


2 Answers

Python's standard library's datetime module is deliberately limited to non-controversial aspects that aren't changing all the time by legislative fiat -- that's why it deliberately excludes direct support for timezones, DST, fuzzy parsing and ill-defined arithmetic (such as "one month later"...) and the like. On top of it, dateutil for many kinds of manipulations, and pytz for timezones (including DST issues), add most of what you're asking for, though not extremely explosive things like "holidays" which vary so wildly not just across political jurisdictions but even across employers within a simgle jurisdiction (e.g. in the US some employers consider "Columbus Day" a holiday, but many don't -- and some, with offices in many locations, have it as a holiday on some locations but not in others; given this utter, total chaos, to expect to find a general-purpose library that somehow magically makes sense of the chaos is pretty weird).

like image 177
Alex Martelli Avatar answered Sep 30 '22 03:09

Alex Martelli


Take a look at the dateutil and possibly mx.DateTime packages.

like image 21
mhawke Avatar answered Sep 30 '22 04:09

mhawke