This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author primal
Recipients cryvate, gabhcosta, primal, tim.peters, veky
Date 2021-07-18.15:11:48
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1626621108.53.0.402907248362.issue44663@roundup.psfhosted.org>
In-reply-to
Content
The difference between the two is the difference between your local time and utc.

datetime.now(timezone.utc)

This returns the current time in utc and is timezone aware. So the timestamp can figure out the seconds since epoch taking into account the timezone.


datetime.utcnow()

Returns the current utc time but is not timezone aware. When timestamp  method is run, it is interpreted as a local timestamp.

This is explained in the docs but perhaps it should be made clearer that
datetime.utcnow().timestamp() is incorrect and would cause bugs. 

I'm not sure about changing the behaviour of utcnow to return a timezone-aware dt as is it could cause hard to detect bugs in existing code. But I did have issues recently where I was using utcnow until I went back and read the docs and changed to datetime.now(timezone.utc). So it's probably a common trap to fall into.

From the docs:

"
Naive datetime instances are assumed to represent local time #

Note There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
or by calculating the timestamp directly:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)"


Warning Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling datetime.now(timezone.utc).
"
History
Date User Action Args
2021-07-18 15:11:48primalsetrecipients: + primal, tim.peters, veky, cryvate, gabhcosta
2021-07-18 15:11:48primalsetmessageid: <1626621108.53.0.402907248362.issue44663@roundup.psfhosted.org>
2021-07-18 15:11:48primallinkissue44663 messages
2021-07-18 15:11:48primalcreate