[issue2736] datetime needs an "epoch" method

Alexander Belopolsky report at bugs.python.org
Thu Apr 7 20:32:02 CEST 2011


Alexander Belopolsky <belopolsky at users.sourceforge.net> added the comment:

On Thu, Apr 7, 2011 at 6:20 AM, Velko Ivanov <report at bugs.python.org> wrote:
..
>> Converting datetime values to float is easy.   If your dt is a naive instance representing UTC time:
>>
>>     timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
>>
>> If your dt is an aware instance:
>>
>>     timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
>
> Please add these lines to the datetime module's documentation. In some
> central, well lit place. I believe that if nothing else, the whole
> discussion should have proved to you that there are many people looking
> for them.

This is precisely what I suggested at the end of msg132697 above.  See
attached patch (issue2736-doc.diff) for a proposed documentation
enhancement.

----------
Added file: http://bugs.python.org/file21565/issue2736-doc.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue2736>
_______________________________________
-------------- next part --------------
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -720,6 +720,22 @@
    out of the range of values supported by the platform C :c:func:`gmtime` function.
    It's common for this to be restricted to years in 1970 through 2038. See also
    :meth:`fromtimestamp`.
+
+   On the POSIX compliant platforms, ``utcfromtimestamp(timestamp)``
+   is equivalent to the following expression::
+
+     datetime(1970, 1, 1) + timedelta(seconds=timestamp)
+
+   There is no method to obtain the timestamp from a :class:`datetime`
+   instance, but POSIX timestamp corresponding to a :class:`datetime`
+   instance ``dt`` can be easily calculated as follows.  For a naive
+   ``dt``::
+
+      timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
+
+   And for an aware ``dt``::
+
+      timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)
 
 
 .. classmethod:: datetime.fromordinal(ordinal)


More information about the Python-bugs-list mailing list