numpypandasdatetime64

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¨)

Solution

  • In [2]: pd.to_datetime(1349863207154117,unit='us')
    Out[2]: Timestamp('2012-10-10 10:00:07.154117')
    
    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')
    
    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')
    
    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')