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.

classification
Title: datetime object does not preserve POSIX timestamp
Type: behavior Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: belopolsky, gpetty, p-ganssle
Priority: normal Keywords:

Created on 2020-06-25 21:22 by gpetty, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg372387 - (view) Author: Grant Petty (gpetty) Date: 2020-06-25 21:22
For complete context, see https://stackoverflow.com/questions/62582386/how-do-i-get-a-naive-datetime-object-that-correctly-uses-utc-inputs-and-preserve

Short version: It does not seem correct that a datetime object produced *from* a POSIX timestamp using utcfromtimestamp should then return a different timestamp.  As a user, I would like to be able to count on the POSIX timestamp as being the one conserved property of a datetime object, regardless of whether it is naive or time zone aware.

> dt0 = dt.datetime(year=2020, month=1, day=1,hour=0,minute=0, tzinfo=pytz.utc)
> print(dt0)

2020-01-01 00:00:00+00:00

> ts0 = dt0.timestamp()
> print(ts0)

1577836800.0

> dt1 = dt.datetime.utcfromtimestamp(ts0)
> print(dt1)

2020-01-01 00:00:00

> ts1 = dt1.timestamp()
> print(ts1)

1577858400.0
msg372396 - (view) Author: Paul Ganssle (p-ganssle) * (Python committer) Date: 2020-06-26 00:49
There's a pretty clear warning on the documentation that utcfromtimestamp is unsuitable for this purpose: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp

What you want is a datetime that knows what time zone it's in, so that it can be translated back into the absolute number of seconds since UTC. The correct way to do that is to tell the datetime it's in UTC by attaching the `datetime.timezone.utc` object (or any equivalent `tzinfo`).

I have written a blog post explaining in detail why you should not use `utcnow` or `utcfromtimestamp`: https://blog.ganssle.io/articles/2019/11/utcnow.html

Hopefully that is helpful to you.
History
Date User Action Args
2022-04-11 14:59:32adminsetgithub: 85290
2020-06-26 00:49:33p-gansslesetstatus: open -> closed
resolution: not a bug
messages: + msg372396

stage: resolved
2020-06-26 00:37:12xtreaksetnosy: + belopolsky, p-ganssle
2020-06-25 21:22:13gpettycreate