Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating tz aware pandas timestamp objects from an integer

I have a integer that is the number of microseconds after the unix epoch. (in GMT)

How can I convert 1349863207154117 using astype to a pandas.Timestamp("2012-10-10T06:00:07.154117", tz=¨UTC¨)? The documentation on astype is not very thorough. I have tried the following.

x = 1349863207154117
dt64 = np.int64(x).astype("M8[us]")
print dt64

returns:

np.datetime64("2012-10-10T06:00:07.154117-0400")
  1. if I only want seconds, this works:
time = pd.Timestamp(datetime.datetime.fromtimestamp(int(x / 1e6)), tz=¨UTC¨)
like image 638
Michael WS Avatar asked May 20 '26 15:05

Michael WS


1 Answers

  • Pandas: Epoch timestamps covers this.
In [2]: pd.to_datetime(1349863207154117,unit='us')
Out[2]: Timestamp('2012-10-10 10:00:07.154117')
  • If you want this in a local timezone
In [6]: pd.to_datetime(1349863207154117,unit='us').tz_localize('US/Eastern')
Out[6]: Timestamp('2012-10-10 10:00:07.154117-0400', tz='US/Eastern')
  • If your time is in UTC, but you want it in another tz.
In [9]: pd.to_datetime(1349863207154117,unit='us').tz_localize('UTC').tz_convert('US/Eastern')
Out[9]: Timestamp('2012-10-10 06:00:07.154117-0400', tz='US/Eastern')
  • Or this
In [10]: pd.to_datetime(1349863207154117,unit='us',utc=True).tz_convert('US/Eastern')
Out[10]: Timestamp('2012-10-10 06:00:07.154117-0400', tz='US/Eastern')
like image 142
Jeff Avatar answered May 22 '26 11:05

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!