0

We store our time values in database as a 13 digit unix epoch at utc. So when I fetch those values to process in python, I need them to be sensitive to timezone.

For example, when I convert a epoch value to datetime, it gives me a naive(timezone insensitive) datetime object. and after that once try to convert it into some other native time format, it messes up the calculations. (Cause my local pc is not in utc timezone)

>>>from datetime import datetime
>>>dt = datetime.utcfromtimestamp(1691868688457/1000)
>>>dt.astimezone(pytz.timezone('America/Chicago'))

the output comes out as:

datetime.datetime(2023, 8, 12, 9, 1, 28, 457000, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)

where as it should have been:

datetime.datetime(2023, 8, 12, 14, 31, 28, 457000, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)

is there any way to read epoch value in timezone sensitive way? for now I am just converting it by a crude way like:


dt = datetime(year=dt.year, month=dt.month, day=dt.day,
             hour=dt.hour, minute=dt.minute, second=dt.second,
             microsecond=dt.microsecond, tzinfo=pytz.utc)
Bubble3D
  • 14
  • 3
  • Useful background about why `utcfromtimestamp` doesn't give you what you might expect: https://blog.ganssle.io/articles/2019/11/utcnow.html. Note also the warning in the docs: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp – slothrop Aug 12 '23 at 20:56
  • for your specific case see [here](https://stackoverflow.com/a/65076703/10197418) – FObersteiner Aug 13 '23 at 09:19

1 Answers1

2

Use fromtimestamp with the tz argument instead to get an aware datetime object:

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

If tz is not None, it must be an instance of a tzinfo subclass, and the timestamp is converted to tz’s time zone.

>>> from datetime import timezone
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(1691868688457/1000, timezone.utc)
>>> dt
datetime.datetime(2023, 8, 12, 19, 31, 28, 457000, tzinfo=datetime.timezone.utc)
>>> dt.astimezone(ZoneInfo("America/Chicago"))
datetime.datetime(2023, 8, 12, 14, 31, 28, 457000, tzinfo=zoneinfo.ZoneInfo(key='America/Chicago'))
sky
  • 46
  • 5