How to convert from Unix epoch time and account for daylight saving time in Python?

I have a large database with thousands of records. Each record contains a Unix epoch time.

The database was created in a single time zone, but that time zone has “daylight saving time” during which the local time is adjusted by an hour for several months.

In Python, I want to convert all those epoch times to the correct local time in that time zone, taking into account “daylight saving time”. I am new to Python.

Important: Some of the dates were recorded during “daylight saving time” and some of the dates were recorded during “standard time”.

Currently, my code is:

import time
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_from_database))

(where time_from_database is the Unix epoch time obtained from the database)

How can this be achieved in Python?

Answer

The operating system has support for time zone conversions, and Python can use that. You don’t need to handle it in your Python code.

You get to it using the pytz module. It is also preferred to use the datetime object.

import pytz
from datetime import datetime

MYTZ = "America/Los_Angeles"
TS = 1631491515.6691816

tzinfo = pytz.timezone(MYTZ)

t = datetime.fromtimestamp(TS, tzinfo)
print(t)

2021-09-12 17:05:15.669182-07:00