转换(来回)UNIX时间戳到系列

时间:2016-11-14 14:58:13

标签: python datetime pandas unix-timestamp

我正在使用python 3.5.2,pandas 0.18.1和sqlite3。

在我的数据库中,自1970年以来我有一个unix_timeINT秒。理想情况下我想从sqlite读取我的数据帧,然后创建一个time列对应于我只会用于某些处理的datetime列的pandas.tslib.Timestampunix_time转换,然后在保存数据帧之前删除。

问题是当解析 unix_time列时使用:

df = pd.read_from_sql_query("SELECT * FROM test", con, parse_dates=['unix_time'])

我获得的pandas.tslib.Timestamp类型对我的处理很好,但之后我必须使用以下方式重新创建原始unix_time列:

df['unix_time'][i] = (df['unix_time'][i] - datetime(1970,1,1)).total_seconds()

真的很脏'

第一个问题:你有更好的方法吗?

我考虑放弃unix时间格式并仅使用datetime格式,但pandas中的to_datetime方法实际上返回pandas.tslib.Timestamp ...无论如何,这样做会迫使我迭代所有行,这是一个糟糕的解决方案。 (除了数据框的单个单元格上的视图之外,不可能将to_datetime应用于其他内容

第二个问题:是否可以在系列中应用它?

我的最后一次尝试是直接使用df['time'] = datetime.datetime.fromtimestamp(df['unix_time']),但令人惊讶的是,它还会返回pandas.tslib.Timestamp

最后,知道我只能保存unix时间戳或日期时间,我目前唯一的选择是:

  • 解析但后来必须将它们转换回unix时间戳 之一。

  • 或者不解析它,但必须将它们转换为pandas.tslib.Timestamp 一个接一个。

如果我可以转换整个系列,那就太好了。

上一个问题:有没有办法将unix时间戳系列转换为datetime(或至少pandas.tslib.Timestamp)或pandas.tslib.Timestamp(或{ {1}})unix时间戳系列?

由于

编辑: 在我处理期间,我提取了一个我想要追加到我的数据集的行。显然,当从数据框传递到系列时,对datetime的转换会隐式添加:

pandas.tslib.Timestamp

返回

df = pd.DataFrame({'UNX':pd.date_range('2016-01-01', freq='9999S', periods=10).astype(np.int64)//10**9})
df['Date'] = pd.to_datetime(df.UNX, unit='s')
print(df.Date.dtypes)
print(type(df['Date'][0]))
test = df.iloc[0]
print(type(test.Date))
new_df = test.to_frame().transpose()   #from here, impossible to do : new_df.to_sql("test", con) because the type for 'Date' is not supported
print(new_df.Date.dtypes)

有没有办法转换&#39;日期&#39;在datetime64[ns] <class 'pandas.tslib.Timestamp'> <class 'pandas.tslib.Timestamp'> object new_dfpandas.tslib.Timestampdatetime64[ns](或只是datetime.datetime)?

2 个答案:

答案 0 :(得分:1)

IIUC你可以这样做:

In [96]: df = pd.DataFrame({'UNX':pd.date_range('2016-01-01', freq='9999S', periods=10).astype(np.int64)//10**9})

In [97]: df
Out[97]:
          UNX
0  1451606400
1  1451616399
2  1451626398
3  1451636397
4  1451646396
5  1451656395
6  1451666394
7  1451676393
8  1451686392
9  1451696391

将UNIX纪元转换为Python日期时间:

In [98]: df['Date'] = pd.to_datetime(df.UNX, unit='s')

In [99]: df
Out[99]:
          UNX                Date
0  1451606400 2016-01-01 00:00:00
1  1451616399 2016-01-01 02:46:39
2  1451626398 2016-01-01 05:33:18
3  1451636397 2016-01-01 08:19:57
4  1451646396 2016-01-01 11:06:36
5  1451656395 2016-01-01 13:53:15
6  1451666394 2016-01-01 16:39:54
7  1451676393 2016-01-01 19:26:33
8  1451686392 2016-01-01 22:13:12
9  1451696391 2016-01-02 00:59:51

datetime转换为UNIX纪元:

In [100]: df['UNX2'] = df.Date.astype('int64')//10**9

In [101]: df
Out[101]:
          UNX                Date        UNX2
0  1451606400 2016-01-01 00:00:00  1451606400
1  1451616399 2016-01-01 02:46:39  1451616399
2  1451626398 2016-01-01 05:33:18  1451626398
3  1451636397 2016-01-01 08:19:57  1451636397
4  1451646396 2016-01-01 11:06:36  1451646396
5  1451656395 2016-01-01 13:53:15  1451656395
6  1451666394 2016-01-01 16:39:54  1451666394
7  1451676393 2016-01-01 19:26:33  1451676393
8  1451686392 2016-01-01 22:13:12  1451686392
9  1451696391 2016-01-02 00:59:51  1451696391

检查:

In [102]: df.UNX.eq(df.UNX2).all()
Out[102]: True

答案 1 :(得分:0)

Pandas Timestamp 和 Unix Seconds 之间的往返(自 1970-01-01):

date_in = pd.to_datetime("2022-04-07")
# type(date_in) is: pandas._libs.tslibs.timestamps.Timestamp
unix_seconds = date_in.value//10**9
date_out = pd.to_datetime(unix_seconds, unit="s")

输出:

date_in
Out[1]: Timestamp('2021-04-07 00:00:00')
unix_seconds
Out[2]: 1617753600
date_out
Out[3]: Timestamp('2021-04-07 00:00:00')