Better datetime handling

I've had these patches around for some time. I don't remember why I never sent a pull request.

The tests included provide evidence that this implementation is preferable to the existing one.