【问题标题】:How to convert a dataframe into datetime format如何将数据框转换为日期时间格式
【发布时间】:2020-05-13 10:24:15
【问题描述】:

我有这个数据框:

3_21_19_59
1
4
22
25
28
31
34
37
.
.
.
.

它有 410 行。

3_21_19_59 中:3 表示月份,21 表示日期,19 是小时,59 是分钟。以下行中的数字:1422... 是秒。

现在,我想将此数据框转换为如下日期时间格式:

2020-03-21 19:59:00
2020-03-21 19:59:01
2020-03-21 19:59:04
2020-03-21 19:59:22
2020-03-21 19:59:25
2020-03-21 19:59:28
...
...
...

等等。 60 秒后,分钟应自动递增。例如:如果是 64 秒,应该是 2020-03-21 19:60:04

任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x pandas data-science datetime-format


    【解决方案1】:

    首先通过to_datetime 使用格式和errors='coerce' 参数转换日期时间,因此对于不匹配的值会丢失值。然后转发填写他​​们以回复datetimes

    然后处理seconds - 首先通过to_numeric 转换为数字,然后通过to_timedelta 转换为时间增量,最后添加到日期时间:

    print (df)
              col
    0  3_21_19_59
    1           1
    2           4
    3          22
    4          25
    5          28
    6          31
    7          34
    8          37
    
    d = pd.to_datetime('20_' + df['col'], format='%y_%m_%d_%H_%M', errors='coerce').ffill()
    td = pd.to_numeric(df['col'],  errors='coerce').fillna(0)
    
    df['col'] = d.add(pd.to_timedelta(td, unit='s'))
    print (df)
                      col
    0 2020-03-21 19:59:00
    1 2020-03-21 19:59:01
    2 2020-03-21 19:59:04
    3 2020-03-21 19:59:22
    4 2020-03-21 19:59:25
    5 2020-03-21 19:59:28
    6 2020-03-21 19:59:31
    7 2020-03-21 19:59:34
    8 2020-03-21 19:59:37
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2019-09-03
      相关资源
      最近更新 更多