There exists a datetime.datetime.fromtimestamp() and many a time I've wondered why there is no .totimestamp() equivalent. The answer is that not all datetime objects can be represented by a timestamp. But if you know this restriction and want it anyway, this is the magic:


Would be so cool if the docs actually mentioned this.

PS: Both functions have a utc variant too



This solution does not give you sub-second resolution, but otherwise is rather elegant. Funny thing is that the %s specifier is not documented by the stdlib, but seems to exist on the underlying implementations at least on UNIX.

And for completeness, these issues are being discussed in the bug tracker. See issue2736 and issue1673409.