【问题标题】:timestamp parsing时间戳解析
【发布时间】:2021-06-30 16:38:27
【问题描述】:

我有一个庞大的数据集,我正在尝试将时间戳列解析为以下格式: YYYY-MM-DD HH:MM:SS:DEC 但我在数据框中的输出类似于:210309_131046520_11

因此:我想将输出列拆分为以下列:

date,  day,  month,  year, dec,  hh,  mm, ss

例如:210309_131046520_11

date 21-03-09
day 09
month 03
year 2021
dec 520
hh 13
@ 987654331@10
ss46

我尝试使用datetime 模块,但似乎没有任何帮助。有人可以帮忙吗?

我的时间戳列示例:

0      210309_131046520_11.sgy
1      210309_131046520_05.sgy
2      210309_131046528_02.sgy
3      210309_131046528_12.sgy
4      210309_131049712_07.sgy
...
162    210309_132658584_07.sgy
163    210309_132659632_10.sgy
164    210309_132701232_05.sgy
165    210309_132704256_02.sgy
166    210309_132707136_12.sgy

我的日期列示例:

0      131046520
1      131046520
2      131046528
3      131046528
4      131049712
...
162    132658584
163    132659632
164    132701232
165    132704256
166    132707136

我尝试过的一件事:

使用split:

s_df["date"] = s_df["timestamp"].apply(lambda row: row.split("_")[1])

输出:

TypeError: list indices must be integers or slices, not str

【问题讨论】:

    标签: python pandas dataframe parsing timestamp


    【解决方案1】:

    您可以使用 datetime 的 strptime 来解释标准库中的日期:

    from datetime import datetime as dt
    dt.strptime('210309_131045620', '%y%m%d_%H%M%S%f')
    
    Out: datetime.datetime(2021, 3, 9, 13, 10, 45, 620000)
    

    在 pandas 数据帧中,使用内置的更有效地实现了这一点,它符合相同的格式化语法:

    import pandas as pd
    pd.to_datetime(df['date'], format='%y%m%d_%H%M%S%f')
    

    有关自定义格式字符串的详细信息,请参阅 strftime 参考:https://strftime.org

    【讨论】:

    • 非常感谢!但是在使用 pandas 时出现以下错误:TypeError: to_datetime() got an unexpected keyword argument 'datetime_format'
    • 谢谢@anky :),也更新了答案
    • 另一个问题,有没有办法格式化数据以删除所有数据输出的(_07.sgy)?
    • @Ayy,绝对!为此,我建议使用正则表达式:re.sub(r'_\d{2}.sgy', '', '210309_131046520_11.sgy') -> '210309_131046520'
    • 哇非常感谢!!!如果我想为整个列删除它,我会替换 e.sub(r'_\d{2}.sgy', '', 'df['timestamp')? @rgk
    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 2015-04-02
    • 2018-07-02
    • 2017-11-22
    • 2021-12-18
    • 2021-11-05
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多