简体   繁体   中英

Convert np.array of Unix Epoch timestamps to Date Time with correct Timezone [PYTHON, NUMPY]

I have an array of Unix Epoch time stampts that I need to convert to datetime format in python.

I can make the conversion ok using numpy and pandas, as below:

tim = [1627599600,1627599600,1627599601,1627649998,1627649998,1627649999]
tim_np = np.array(tim)
tim_np = np.asarray(tim, dtype='datetime64[s]',)
tim_pd = pd.to_datetime(tim,unit='s', utc=True,)

print(tim_np)
print(tim_pd)

The problem I am running into is that the time zone is wrong, I am in NY so require it set to "EST".

I tried addressing by setting utc=True in the pd.to_datetime function but it still keeps defaulting to "GMT" ( 5 hours ahead).

I also tried the datetime.fromtimestamp(0) but it seemingly only works on single elements and not arrays - https://note.nkmk.me/en/python-unix-time-datetime/

Is there any efficient method to set the time zone when converting epochs?

Found that this can be achieved with pandas using the.tz_* methods:

.tz_localie - https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.tz_localize.html

.tz_convert - https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.tz_convert.html

Working code:

tim = [1627599600,1627599600,1627599601,1627649998,1627649998,1627649999]

tim_pd = (pd.to_datetime(tim,unit='s')
            .tz_localize('utc')
            .tz_convert('America/New_York'))

print(tim_pd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM