Reputation: 1874
I have epoch time which I need to convert to local time (US/Pacific). I get the following results using pandas to_datetime()
function and datetime.datetime.fromtimestamp()
.
datetime.datetime.fromtimestamp(1554782410.0370002)
Out[704]: datetime.datetime(2019, 4, 8, 21, 0, 10, 37000)
pd.to_datetime(1554782410.0370002, unit='s')
Out[705]: Timestamp('2019-04-09 04:00:10.037000179')
Note that the time difference is 7:00 hrs between the two output. How do I reconcile the two?
Any help would be greatly appreciated.
Thanks.
Upvotes: 0
Views: 50
Reputation: 11171
I prefer to define in UTC (tz aware) then convert:
pd.to_datetime(1554782410.0370002, unit='s', utc=True).tz_convert('US/Pacific')
The obvious thing you dont want to do manually subtract hours. If you happen to move, or your code runs on a server in another timezone, it will fail if you manually subtract off the hours. In short: use a package/api for timezone management if you want timezone-aware times.
Upvotes: 1
Reputation: 1432
Two options as I see it:
First is to manually subtract 7 hours using pd.Timedelta()
:
pd.to_datetime(1554782410.0370002, unit='s') - pd.Timedelta(hours=7)
Second would be to convert it to local time zone from UTC time using tz_localize
and tz_convert
. I think this method is slower, but does have the advantage of not worrying about calculating time difference manually or worrying about DST:
pd.to_datetime(1554782410.0370002, unit='s', utc=True).tz_convert('America/Los_Angeles')
Upvotes: 0