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?
Example 1: Python timestamp to datetime The fromtimestamp() function is used to return the date associated with a given timestamp. The date class's function fromtimestamp() computes and returns the date and time corresponding to a specified timestamp. The timestamps in this example range from 1970 to 2038.
To remove timestamp, tzinfo has to be set None when calling replace() function.
timedelta Objects. A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With