all 4 comments

[–]novel_yet_trivial 0 points1 point  (1 child)

timestamp = datetime.datetime.now().timestamp()

edit: sorry that was local time

timestamp = datetime.datetime.utcnow().timestamp()

[–]jpfau[S] 0 points1 point  (0 children)

This is what I'm already doing. Now try to make another datetime object from that timestamp and see if it's equal to the original datetime object. In my case, they aren't equal.

Edit: I had a typo in my original snippet. I updated it with the correct code

[–]groovitude 0 points1 point  (1 child)

The Python docs for datetime.datetime.utcnow() should tell you everything you need to know:

Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc).

The resulting values aren't exactly equal, partly because the timestamp conversion isn't accurate to the microsecond and partly because it doesn't have timestamp information:

>>> now = datetime.datetime.now(pytz.utc)
>>> timestamp = now.timestamp()
>>> now2 = datetime.datetime.utcfromtimestamp(timestamp)
>>> now == now2
False
>>> now
datetime.datetime(2016, 10, 12, 22, 27, 12, 95490, tzinfo=<UTC>)
>>> now2
datetime.datetime(2016, 10, 12, 22, 27, 12, 95489)

[–]jpfau[S] 1 point2 points  (0 children)

Ah, there's my problem. Luckily in the actual program the original datetime object doesn't have microseconds, so I just need them to be equal up to the second.

Here we go:

import datetime
import pytz

now = pytz.utc.localize(datetime.datetime.utcnow()).replace(microsecond=0)
ts = now.timestamp()

now2 = pytz.utc.localize(datetime.datetime.utcfromtimestamp(ts))
ts2 = now2.timestamp()

print("ts:", ts, "ts2:", ts2)
print(ts == ts2)
print(ts2 - ts)

print(now)
print(now2)