farthVader
farthVader

Reputation: 908

Correct usage of utc timestamps and local datetime

I've used time.time() to generate timestamps across client apps. These timestamps are accumulated and sent in batches to an external and independent location.

While rendering these timestamps back on the client application I intend to use datetime.fromtimestamp(ts_from_external_source) in order to create local datetime objects, without defining the timezone so it assumes the local by default.

Is this the recommended way of doing it?

Upvotes: 1

Views: 142

Answers (2)

jfs
jfs

Reputation: 414179

It is ok to use a naive datetime object that represents local time if you use it only for displaying the timestamp.

datetime.fromtimestamp(ts_from_external_source) should work during DST transitions (local time may be ambiguous but POSIX timestamps are not if we ignore leap seconds). Though it might fail for dates from the past/future if the local timezone had/will have different UTC offset at the time and the underlying C library does not use a historical timezone database such as the tz database (Linux, OS X use it. python on Windows -- might not).

datetime.fromtimestamp(ts_from_external_source) should be ok for recent dates in most timezones.

You could use Europe/Moscow timezone with dates from 2010-2015 for testing (the timezone rules had changed in that period).

You could provide the tz database using pytz module:

from datetime import datetime, timedelta
from tzlocal import get_localzone # $ pip install tzlocal
import pytz # $ pip install pytz

tz = get_localzone() # get the local timezone as pytz timezone (with historical data)
utc_dt = datetime(1970, 1, 1, tzinfo=pytz.utc) + timedelta(seconds=ts_from_external_source)
dt = utc_dt.astimezone(tz)

Or:

dt = datetime.fromtimestamp(ts_from_external_source, tz)

Run these tests to see whether datetime + timedelta and fromtimestamp() produce different results on your platform.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249133

Yes that's a good way of doing it: you store "Unix epoch" style times, and convert them to whatever local time you need before displaying them.

Upvotes: 0

Related Questions