gpt4 book ai didi

python - Pandas 日期时间到 unix 时间戳秒

转载 作者:太空狗 更新时间:2023-10-29 22:24:14 27 4
gpt4 key购买 nike

来自pandas.to_datetime的官方文档我们可以说,

unit : string, default ‘ns’

unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer orfloat number. This will be based off the origin. Example, withunit=’ms’ and origin=’unix’ (the default), this would calculate thenumber 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]

后者的输出没有变化。每次它显示日期时间值而不是第二个 unix 纪元开始的毫秒数。这是为什么?我错过了什么吗?

最佳答案

我认为您误解了论点的意义。 origin='unix' 的目的是将整数时间戳转换为 datetime,而不是相反。

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

这里有一些选项:

选项 1:整数除法

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

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

优点:

  • super 快

缺点:

  • 对 pandas 如何在内部存储日期做出假设

方案二:pandas推荐

Pandas docs推荐使用以下方法:

# create test data
dates = pd.to_datetime(['2019-01-15 13:30:00'])

# calculate unix datetime
(dates - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')

[out]:
Int64Index([1547559000], dtype='int64')

优点:

  • “地道”,图书馆推荐

缺点:

  • 笨重
  • 性能不如整数除法

选项 3:pd.Timestamp

如果您只有一个日期字符串,您可以使用 pd.Timestamp,如其他答案所示:

pd.Timestamp('2019-01-15 13:30:00').timestamp()
# 1547559000.0

如果您必须强制多个日期时间(其中 pd.to_datetime 是您唯一的选择),您可以初始化并映射:

pd.to_datetime(['2019-01-15 13:30:00']).map(pd.Timestamp.timestamp)
# Float64Index([1547559000.0], dtype='float64')

优点:

  • 单个日期时间字符串的最佳方法
  • 容易记住

缺点:

  • 性能不如整数除法

关于python - Pandas 日期时间到 unix 时间戳秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54313463/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com