9

Python's datetime class has a fromtimestamp method to create a datetime object from a timestamp, but doesn't provide a totimestamp method for the other way round... I'm aware that with something like time.mktime(x.timetuple()) you can convert the datetime object to a timestamp, but this looks unnecessary complicated to me, so I'm curious why there is no totimestamp method?

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • See also http://stackoverflow.com/questions/8022161/python-converting-from-datetime-datetime-to-time-time – Sven Marnach Nov 23 '11 at 14:54
  • @Sven: My question isn't about asking for methods to convert it, but wanting to know the reason for the absence of such a method in the `datetime` module... – Bernhard Vallant Nov 23 '11 at 14:56
  • 1
    I didn't say this is a duplicate. I just linked related information, which is always useful for people hitiing this page from Google. – Sven Marnach Nov 23 '11 at 15:01

1 Answers1

13

I do remember a discussion/bug report about this thing while I wondered about this some time back. Long story short: plenty of proposals have been made, but for some reason, none have been accepted.

The point is I think best summed up in this reply:

Plenty have proposed a satisfactory solution. No one has come up with a solution that is satisfactory to you, because you have overconstrained the problem. The reason we still have no utctotimestamp() after all these years is that you, and you alone as far as I know, refuse to accept a method that inverts utcfromtimestamp() with microsecond precision over its working range. Such a method is a perfectly reasonable and acceptable solution and would add a lot of value to Python as a language.

I suspect you don't realize just how much pain you have unintentionally caused the world of Python users by singlehandedly blocking progress on this issue. I've seen them: students, friends, coworkers -- even very smart and capable people are stymied by it. No one thinks of looking in the calendar module. Maybe if you watched some of them struggle with this, you would understand.

The end result to this story was that documentation was added on how to do it yourself:

# 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 `datetime` instance,
# but POSIX timestamp corresponding to a `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)
Community
  • 1
  • 1
jro
  • 9,300
  • 2
  • 32
  • 37