88912

python: utcfromtimestamp vs fromtimestamp, when the timestamp is based on utcnow()

<h3>Question</h3>

Pretty sure it's an easy one but I don't get it.

My local TZ is currently GMT+3, and when I take timestamp from datetime.utcnow().timestamp() it is indeed giving me 3 hours less than datetime.now().timestamp()

During another process in my flow, I take that utc timestamp and need to turn it into datetime.

When I'm doing fromtimestamp I get the right utc hour, but when I'm using utcfromtimestamp I get another 3 hours offset.

The documentation, though, asks me to use fromtimestamp for local timezone, and utcfromtimestamp for utc usages.

What am I missing ? is the initial assumption for both funcs is that the timestamp is given in local timezone ?

Thank you :)


<h3>Answer1:</h3>

The key thing to notice when working with datetime objects and their POSIX timestamps at the same time is that naive datetime objects (the ones without timezone information) are assumed by Python to refer to local time (OS setting). In contrast, a POSIX timestamp (should) always refer to UTC seconds since the epoch. You can unambiguously obtain it by time.time(). In your example, not-so-obvious things happen:

1) datetime.now().timestamp() - now() gives you a naive datetime object that resembles local time. If you call for the timestamp(), Python converts the datetime to UTC and calculates the timestamp for that.

2) datetime.utcnow().timestamp() - utcnow() gives you a naive datetime object that resembles UTC. However, if you call timestamp(), Python assumes (since naive) that the datetime is local time - and converts to UTC again before calculating the timestamp! The resulting timestamp is therefore off from UTC by twice your local time's UTC offset...

A code example. Let's make some timestamps. Note that I'm on UTC+2, so offset is -7200 s.

import time from datetime import datetime, timezone ts_ref = time.time() # reference POSIX timestamp ts_utcnow = datetime.utcnow().timestamp() # dt obj UTC but naive - so also assumed local ts_now = datetime.now().timestamp() # dt obj naive, assumed local ts_loc_utc = datetime.now(tz=timezone.utc).timestamp() # dt obj localized to UTC print(int(ts_utcnow - ts_ref)) # -7200 # -> ts_utcnow doesn't refer to UTC! print(int(ts_now - ts_ref)) # 0 # -> correct print(int(ts_loc_utc - ts_ref)) # 0 # -> correct

I hope this clarifies that if you do datetime.utcfromtimestamp(ts_utcnow), you get double the local time's UTC offset. Python assumes (which I think is pretty sane) that the timestamp refers to UTC - which in fact, it does not.

My suggestion would be to use timezone-aware datetime objects; like datetime.now(tz=timezone.utc). The dateutil library can also be very helpful when working with datetime and timezones. And if you want to dig deep, have a look at the datetime src code. That could also help clarifying the issue you encountered.

来源:https://stackoverflow.com/questions/62286398/python-utcfromtimestamp-vs-fromtimestamp-when-the-timestamp-is-based-on-utcnow

Recommend

  • Display foreach loop iteration number in SSIS
  • static classes and multiple instances on azure
  • Navigation item title view - same for all pushed view controllers
  • Elixir: rationale behind allowing rebinding of variables
  • Xcode - change bundle identifier but not product name
  • MSBuild / Visual Studio distributed builds
  • Medical Values: 1 Super Exam Table or Lots of Exam Tables
  • How to configure the CKEditor under XPages?
  • How to access native iOS file system using Sencha touch 2 alone
  • How to catch crash without disturbing the normal crash flow
  • Troubleshooting HTTPClient asynchronous POST and reading results
  • How to deploy a COM
  • Conditional Redirect on Login
  • How to trigger mysql event after a time period?
  • Reading large text file very slow
  • Limit # of records returned based on a form control
  • Existing data serialized as hash produces error when upgrading to Rails 5
  • JSF validateLength question
  • Coin change recursive approach
  • Using PHP & Tornado
  • Specify the _id field using Bulk.IndexMany in ElasticSearch
  • Battery life if using GPS and background app ios/android
  • jQuery Ajax call to WCF service returning “Method not allowed (405)”
  • separate tokens in batch file
  • playing mp3 from nsbundle
  • How to make Rss News Reader application in android …? [closed]
  • Getting the type of a “Type” in C# reflection
  • How do I use libcurl to printf a remote FTP directory listing?
  • When to use the tag in the head and body section of a html page? [duplicate]
  • Google Spreadsheet Script to Blink a range of Cells
  • Support of :after in IE7
  • How do I add a mouse over tooltip to an Image using .DrawImage()
  • matrix multiplication apache pig
  • Google App Engine backend servlet not responding
  • Unity3d lost directional light shadows after generate assetBundle (.unity3d file)
  • Make checkout phone field optional for specific countries in WooCommerce
  • Excel VBA : conditional formatting of sheet1 cells from sheet2 values in excel 2007
  • multiple button click in asp.net MVC 3
  • Running R's aov() mixed effects model from Python using rpy2
  • How to mutate multiple variables without repeating codes?