pandas datetime到unix时间戳记秒 [英] pandas datetime to unix timestamp seconds

查看:130
本文介绍了 pandas datetime到unix时间戳记秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自 pandas.to_datetime 我们可以说,

unit : string, default ‘ns’

arg的

单位(D,s,ms,us,ns)表示单位,它是整数或 浮点数.这将基于原点. 示例,带有 unit ='ms'和origin ='unix'(默认值),这将计算出 Unix纪元开始的毫秒数.

unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit=’ms’ and origin=’unix’ (the default), this would calculate the number of milliseconds to the unix epoch start.

所以当我这样尝试时,

import pandas as pd
df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]})
df_unix_sec = pd.to_datetime(df['time'],unit='ms',origin='unix')
print(df)
print(df_unix_sec)

                 time
0   2019-01-15 13:25:43
0   2019-01-15 13:25:43
Name: time, dtype: datetime64[ns]

后一输出不变.每次显示datetime值,而不是第二个unix纪元开始的毫秒数.这是为什么?我想念什么吗?

Output is not changing for the later one. Every time it is showing the datetime value not number of milliseconds to the unix epoch start for the 2nd one. Why is that? Am I missing something?

推荐答案

我认为您误解了该参数的含义. origin='unix'的目的是将整数时间戳记转换为 datetime,而不是其他方式.

I think you misunderstood what the argument is for. The purpose of origin='unix' is to convert an integer timestamp to datetime, not the other way.

pd.to_datetime(1.547559e+09, unit='s', origin='unix') 
# Timestamp('2019-01-15 13:30:00')

相反,您可以通过转换为整数(获取纳秒)并除以10 9 来获得时间戳.

Conversely, you can get the timestamp by converting to integer (to get nanoseconds) and divide by 109.

pd.to_datetime(['2019-01-15 13:30:00']).astype(int) / 10**9
# Float64Index([1547559000.0], dtype='float64')


更新

熊猫文档建议使用以下方法:


Update

Pandas docs recommend using the following method:

dates = pd.to_datetime(['2019-01-15 13:30:00'])
(dates - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')  
# Int64Index([1547559000], dtype='int64')

速度不如上面显示的方法快,但这并没有假设熊猫如何在内部存储其datetime对象.

Not as fast as the method shown above, but this makes no assumption about how pandas internally stores its datetime objects.

这篇关于 pandas datetime到unix时间戳记秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆