【问题标题】:Replace Date in Pandas Timestamp替换 Pandas 时间戳中的日期
【发布时间】:2018-06-08 18:22:05
【问题描述】:

我正在尝试从 pandas 数据框中获取准确的时间戳。我的文件具有自一天开始以来以秒为单位的时间戳,并且每个文件的文件名中都有日期。我已经能够使用以下方法将秒转换为小时和分钟: df['time'] = pd.to_datetime(df['sec'], unit='s') 但是 YYMMDD 从纪元开始。我知道时间戳有一个替换功能,但我没有成功让它工作。有没有可能让这样的事情起作用?

df['month']=month
df['day'] = day
df['year'] = 2018
date = '%s-%s-%s '%(year, month, day) + df['sec']
df['time'] = pd.to_datetime(date, unit='s')

或者如何更改时间戳以保持我想要的小时/分钟/秒,但根据文件名/其他列更改日期?

【问题讨论】:

标签: python pandas dataframe timestamp


【解决方案1】:

我们可以将您的第二列转换为纳秒,并通过添加该日期的 pd.Timestamp 值来添加纳秒量。

pd.to_datetime(df['sec']*(10**9) + pd.Timestamp('the date').value)

完整示例:

import pandas as pd

# Suppose we have a filename such as
fname = '2018-01-01.txt'

# Create a csv-file with col sec and values 0,1000,2000
with open(fname,'w') as f:
    f.write('sec\n0\n1000\n2000')       

# Read dataframe
df = pd.read_csv(fname)

# Create datetime column (fname[:-4] = '2018-01-01')
df['datetime'] = pd.to_datetime(df['sec']*(10**9) + pd.Timestamp(fname[:-4]).value)

print(df)

返回:

    sec            datetime
0     0 2018-01-01 00:00:00
1  1000 2018-01-01 00:16:40
2  2000 2018-01-01 00:33:20

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 2016-10-05
    • 2021-01-18
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多