简体   繁体   English

使用 astype(int) 将时间戳转换为 int

[英]Convert a timestamp to int using astype(int)

I have the variable time :我有可变time

>>> time = pd.to_datetime(1613260800000000000)
>>> time
Timestamp('2021-02-14 00:00:00')

time is a timestamp . time是一个timestamp Now I want to convert time back to an int value.现在我想将time转换回一个int值。 But Timestamp object has no attribute astype .但是Timestamp object 没有属性astype Running the following code:运行以下代码:

>>>time.astype(int)

AttributeError: 'Timestamp' object has no attribute 'astype'

I know that for a column of a dataframe I can do:我知道对于 dataframe 的一列我可以这样做:

>>> df['start_time'] = df['start_time'].to_timedate()
>>> df['start_time'] = df['start_time'].astype(int)

The second command assigns the type of the column to int .第二个命令将列的类型分配给int

But I did not find a comprehensive source explaining what to do with individual Timestamp argument.但是我没有找到一个全面的资源来解释如何处理单个Timestamp参数。

How can I solve this issue?我该如何解决这个问题?

just use time_variable.timestamp()只需使用time_variable.timestamp()

but that will be in seconds... instead of ms or whatever (us?)但这将在几秒钟内......而不是 ms 或其他任何东西(我们?)

you will need to multiply the result by 1e9 to get back the same value as you put in您需要将结果乘以1e9以返回与您输入的相同的值

For ns like native format for numpy/pandas use:对于像numpy/pandas的原生格式这样的ns ,请使用:

d = pd.to_datetime(1613260800000000000)

native = int(d.timestamp() * 10**9)
print (native)
1613260800000000000

print (pd.to_datetime(native))
2021-02-14 00:00:00

If need convert column:如果需要转换列:

time = pd.to_datetime(1613260800000000000)

df = pd.DataFrame({'start_time':[time, time]})

print (df['start_time'].astype(np.int64))
0    1613260800000000000
1    1613260800000000000
Name: start_time, dtype: int64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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