Paul Martin <greatestloginnamee...@gmail.com> added the comment:

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).
"

----------
nosy: +primal

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44663>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to