After considerable effort and reading, I came up with the following two functions, one of which is (or is intended to be) the exact inverse of the other. The first takes a Python datetime object (naive) and converts it to integer seconds since the epoch; the other does the reverse:
import datetime
import time
import calendar
def datetime2timestamp(dt):
''' Accepts a naive datetime object and converts it to a time in seconds since the start of 1970'''
return(calendar.timegm(dt.timetuple()))
def timestamp2datetime(ts):
''' Accepts a time in seconds since the start of 1970 and converts it to a naive datetime object'''
return(datetime.datetime.fromtimestamp(time.mktime(time.gmtime(ts))))
>>> dt = datetime.datetime(1970, 1, 1, 0, 0, 1)
>>> print dt
1970-01-01 00:00:01
>>> ts = datetime2timestamp(dt)
>>> print ts
1
>>> dt = timestamp2datetime(ts)
>>> print dt
1970-01-01 00:00:01
Two questions:
1) Is there a way to accomplish the same thing (especially the second function) more simply and without requiring the importing of three different modules? Simpler solutions I had previously found had the defect that they were inconsistent about the distinction between the local time on my computer and UTC.
2) Is there a way to have the timestamp be a float instead of the integer number of seconds returned by calendar.timegm() ?