maynull
maynull

Reputation: 2046

How to handle time.time() in Python?

I'm trying to collect real-time data with hdf5, but it doesn't support datetime for now, so I thought np.float64(timestamp) would be a better option than simple strings, from the standpoint of storage efficiency(8bits vs more than 8 bits). I want to record event times with microsecond precision.

From these web pages(https://docs.python.org/3/library/time.html, https://pymotw.com/2/time/index.html), I read that timestamps that I get by time.time() is calculated in UTC, but now I think something's different from what I read.

from datetime import datetime
import time

print( datetime.utcnow() )

print( datetime.fromtimestamp( time.time() ) )

>>> (executing file "<tmp 2>")
2018-03-16 21:28:34.716853
2018-03-17 06:28:34.716854

I don't understand why they are different. If timestamps are calculated in UTC, I think they should be the same.

I have another question. I'd like to know how to add some amount of time to timestamps. For example, I want to know how to do this with timestamps.

datetime.utcnow() + timedelta(hours=3)

Upvotes: 1

Views: 64

Answers (1)

llllllllll
llllllllll

Reputation: 16424

datetime.utcnow() is the utc time, datetime.fromtimestamp() is the local time, which depends on your time zone.

To add to timestamp, you just need to convert the timedelta to seconds:

time.time() + timedelta(hours=3).total_seconds()

Upvotes: 2

Related Questions